【发布时间】:2014-05-11 01:40:12
【问题描述】:
例如,我希望以下输出数字 6,但我见过的每个运算符重载示例都在参数中包含一个“const”对象。
Class MyClass
{
private:
int num;
public:
//Setter
void setNum(int x) {num = x;}
//Getter
int getNum() {return x;}
//Overloading + Operator
MyClass operator + (int add)
{
}
};
int Main()
{
MyClass test;
test.setNum(2);
test = test + 4;
cout << test.getNum();
return 0;
}
【问题讨论】:
-
参数中没有对象的运算符将是否定运算符或函数运算符,我认为您的问题措辞不正确。
-
您的代码很好,但实际上您必须将一些代码放入
operator+函数中。你确实通过参数传递了add。二进制+运算符必须有两个参数,这是无法绕过的。 -
这个问题很混乱。让您的代码输出
6和const运算符没有矛盾:MyClass operator+(int add) const { MyClass x = *this; x.num += add; return x; }
标签: c++ operator-overloading operator-keyword