我刚刚阅读了有关使用减号 (-)、增量 (++) 等的一元运算符重载的内容。我想写一个相同的代码只是为了练习。但是当我试图运行它时,它给了我减号和增量运算符的错误。我认为问题是我在 main 中调用运算符的方式。任何人都可以吗这样做的正确方法是什么?
#include<iostream>
using namespace std;
class c{
int x;
int y;
public:
c(int a,int b){
x=a;
y=b;
}
void operator -(){
x=x+1;
y=y+1;
}
void display(){
cout<<x<<" "<<y<<"\n";
}
};
int main()
{
c obj(2,3);
obj.display();
obj- ; //I think the error is on this line
obj.display();
return 0;
}
如果我将 obj- 替换为 -obj,则代码可以正常工作。为什么会这样?同样是++ 运算符重载的问题(使用++obj 工作正常但 obj++ 不起作用),为什么?
谢谢。
最佳答案
一元减号运算符 -
只是一个前缀运算符。
要重载 ++
运算符的后缀版本,您需要一个虚拟 int 参数。例如
struct foo
{
void operator - ()
{
std::cout << "hello" << std::endl;
}
void operator ++ (int)
{
std::cout << "world" << std::endl;
}
};
int main()
{
foo bar;
-bar;
bar++;
}
关于c++ - 在 C++ 中重载一元运算符有困难吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10252322/