【发布时间】:2018-08-04 05:02:09
【问题描述】:
#include<iostream>
using namespace std;
class binary
{
protected:
int num;
public:
binary(int a)
{
num=a;
}
binary operator - (binary b1)
{
binary b(0);
b.num=~(b1.num-1);
return b(b.num);
}
void display()
{
cout<<"Negative is: "<<num;
}
};
int main()
{
int a;
cout<<"Enter no.: ";
cin>>a;
binary b(a);
binary b1=-b;
b1.display();
}
在上面的程序中,表明重载运算符的返回类型应该是 int& 的形式。谁能给我解释一下这是什么意思?
【问题讨论】:
-
return b(b.num);不对。应该是return b;。这是您看到错误的地方吗? -
如果要重载一元减号,则为
operator-(),不带参数;操作数是this。 -
operator-()没有必要返回引用。它通常按值返回是合适的,因为表达式a - b给出的结果既不是a也不是b。通常有一个好处(对于二进制operator-()),第二个操作数由const引用传递 - 但这不是你要问的。
标签: c++ return operator-overloading