运算符重载+添加两个对象

Ali*_*Ali 0 c++ operator-overloading

我试图添加两个对象,它们在同一类中。

在班级的私人部分,我有两个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 
Run Code Online (Sandbox Code Playgroud)

我不知道我对一个问题,opeartor+我想

One operator+(const One &a, const One &b){

One c,d,r;

c = a;
d = b;

r += b;
r += a;

return r;
}
Run Code Online (Sandbox Code Playgroud)

我认为以上代码是错误的,但是我尝试使用类似b.num1的方法,但出现编译错误

error: 'int One::num1' is private error: within this context

而且我也不能使用b-> num1,因为上述函数不在成员函数部分中。

error: base operand of '->' has non-pointer type 'const One'
Run Code Online (Sandbox Code Playgroud)

这就是它的呼唤方式 main

Result = LeftObject + RightObject;

Rob*_*obᵩ 5

如果您已经实现了此成员函数:

One One::operator+=(const One&);
Run Code Online (Sandbox Code Playgroud)

然后,您可以这样实现非成员加法运算符:

One operator+(const One& lhs, const One& rhs) {
  One result = lhs;
  result += rhs;
  return result;
}
Run Code Online (Sandbox Code Playgroud)

可以将其简化为以下内容:

One operator+(One lhs, const One& rhs) {
  return lhs += rhs;
}
Run Code Online (Sandbox Code Playgroud)

此模式(您可以适应所有操作员/操作员分配对)将操作员分配版本声明为成员-它可以访问私有成员。它将运算符版本声明为非朋友非成员-这允许在运算符的任何一侧进行类型提升。

Aside:该+=方法应返回对的引用*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";
}
Run Code Online (Sandbox Code Playgroud)

  • 我列出的运算符取决于工作副本构造函数和工作的`operator + =`。是的,如果其中任何一个都不正确,则结果将不正确。 (2认同)