例如,我想输出数字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;
}
答案 0 :(得分:3)
以下是执行所需操作的代码:
class MyClass
{
private:
int num;
public:
//Setter
void setNum(int x) {num = x;}
//Getter
int getNum() {return num;}
//Overloading + Operator
MyClass operator + (int add)
{
MyClass copy;
copy.num = num + add;
return copy;
}
};
int main()
{
MyClass test;
test.setNum(2);
test = test + 4;
std::cout << test.getNum();
return 0;
}
您的代码有许多已修复的编译器错误。例如,Class应该是class,Main应该是main。