运算符重载的问题:int operator+();与int &operator+();有什么区别?

来源:百度知道 编辑:UC知道 时间:2024/07/01 06:54:14
能有具体的例子说明更好!~~~如果换成Sample operator+();与Sample &opetator+();呢?其中Sample是类名...

int operator+()这个表明这个是重载的+运算符,因为重载的操作符需要定义成非成员函数,一般都定义为友元
所以需要返回一个对象,而
int& operator+()应该是内置的+操作符,它只要返回一个成员变量的引用即可
基本数据类型不能重载操作符,下面举个Item类的例子说明如下:
Item operator+(const Item &left, const Item &right)
{ Item temp;
temp.data = left.data + right.data;
return temp;
}

Item& operator+(const Item & var)
{
this->data = this->data + var.data;
return *this;
}

Sample operator+();要重载两个实例对象,Sample &opetator+();重载一个实例对象