我正在尝试添加两个对象,它们属于同一个类。
在课程的私人部分,我有两个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;
答案 0 :(得分:5)
如果您已经实现了此成员函数:
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";
}
答案 1 :(得分:1)
我看不出为什么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();
}