我试图添加两个对象,它们在同一个类中。
在类的私有部分,我有两个int变量
class One {
private:
int num1, num2;
public:
One operator+=(const One&); // - a member operator that adds another One object - to the current object and returns a copy of the current object
friend bool operator==(const One&, const One&); // - a friend operator that compares two One class objects for equality
};
One operator+(const One&, const One&);// - a non-friend helper operator that adds One objects without changing their values and returns a copy of the resulting One 我想我不确定我的opeartor+有问题
One operator+(const One &a, const One &b){
One c,d,r;
c = a;
d = b;
r += b;
r += a;
return r;
}我认为上面的代码是错误的,但是我尝试像b.num1一样使用,但我得到了编译错误
error: 'int One::num1' is private error: within this context
我也不能使用b->num1,因为上面的函数不在成员函数部分。
error: base operand of '->' has non-pointer type 'const One'这就是它在main中的调用方式
Result = LeftObject + RightObject;
发布于 2012-06-27 23:34:27
如果您已经实现了此成员函数:
One One::operator+=(const One&);然后,您可以实现非成员加法运算符,如下所示:
One operator+(const One& lhs, const One& rhs) {
One result = lhs;
result += rhs;
return result;
}这可以简化为以下几点:
One operator+(One lhs, const One& rhs) {
return lhs += rhs;
}此模式(您可以对所有操作符/操作符-赋值对进行调整)将操作符-赋值版本声明为成员--它可以访问私有成员。它将运算符版本声明为非友元非成员--这允许在运算符的两端进行类型提升。
旁白:+=方法应该返回对*this的引用,而不是一个副本。所以它的声明应该是:One& operator+(const One&)。
编辑:下面是一个可用的示例程序。
#include <iostream>
class One {
private:
int num1, num2;
public:
One(int num1, int num2) : num1(num1), num2(num2) {}
One& operator += (const One&);
friend bool operator==(const One&, const One&);
friend std::ostream& operator<<(std::ostream&, const One&);
};
std::ostream&
operator<<(std::ostream& os, const One& rhs) {
return os << "(" << rhs.num1 << "@" << rhs.num2 << ")";
}
One& One::operator+=(const One& rhs) {
num1 += rhs.num1;
num2 += rhs.num2;
return *this;
}
One operator+(One lhs, const One &rhs)
{
return lhs+=rhs;
}
int main () {
One x(1,2), z(3,4);
std::cout << x << " + " << z << " => " << (x+z) << "\n";
}发布于 2012-06-27 23:34:18
我不明白为什么operator+是错误的:
#include <stdio.h>
class One {
public:
One(int n1, int n2): num1(n1),num2(n2) {}
private:
int num1, num2;
public:
One operator+=(const One& o) {
num1 += o.num1;
num2 += o.num2;
return *this;
}
friend bool operator==(const One&, const One&); // - a friend operator that compares two One class objects for equality
void print() {
printf("%d,%d\n", num1, num2);
}
};
One operator+(const One& a, const One& b) {
One r(0,0);
r += b;
r += a;
return r;
}
int main() {
One a(1,2),b(3,4);
One r = a + b;
r.print();
}https://stackoverflow.com/questions/11229701
复制相似问题