18

我已经像这样重载了 + 运算符

class sample
{
private : 
  int x;
public :
  sample(int x1 =0)
  {
    x = x1;
  }

  sample operator+(sample s);
};

sample sample::operator+(sample s)
{
  x = x + s.x;
  return *this;
}

int  main()
{
  sample s1(10);
  sample s2;
  s2 = s2 + s1;
  return 0;    
}

这个对吗?我的问题是如果我想添加两个不同的示例对象,我将如何重载操作符;例如对于s = s1 + s2;

我喜欢s = s + s1 + s2使用现有的实现。

4

1 回答 1

29

使用友元运算符重载应该可以解决问题,并且是定义二元运算符的常用方法,只需添加:

friend sample operator+(const sample& a, const sample& b); //in class

sample operator+(const sample& a, const sample& b) { //outside the class
    return sample(a.x + b.x);
}

如果您希望它保持成员身份(在一些罕见的情况下有缺点,并且没有优点),您必须使操作符成为一个const函数:

sample operator+(sample s) const; //in class

sample sample::operator+(const sample& b) const { //outside the class
    return sample(this->x + b.x);
}

其中任何一个都将允许运算符链接。您之前s = s + s1 + s2失败的原因是s + s1会执行并返回一个临时 sample对象。然后,它会尝试添加s2到该样本中。但是,临时对象只能是const引用[1],因此只能使用const成员函数。由于您的operator+成员函数不是const函数,因此您不能在const临时上使用该函数。请注意,要制作它const,我必须重写它,因为您的版本修改了+.

[1] 例外在这里不是特别相关,即右值

于 2012-06-22T17:56:26.470 回答