c++ - 在没有成员函数的情况下重载一元减号运算符
问题描述
考虑以下程序:
//Operator overloading of unary minus operator- with and without member function
#include <iostream>
using namespace std;
class test{
int x;
public:
test(){
}
test(int h){
this->x=h;
}
friend void operator- (test);
void showData(){
cout << x << endl;
}
};
void operator- (test a){
test *ptr=&a;
ptr->x=-ptr->x;
}
int main(){
test t1(7);
operator-(t1);
t1.showData();
return 0;
}
在执行时,这会在在线编译器和机器上的 Visual Studio Code 上打印 7 而不是 -7。有人可以解释什么是错的吗?
解决方案
如果你想这样做,你test&
不需要。 test
你可能不应该;一元减号不应该改变它的参数,它应该返回一个修改过的参数。
推荐阅读
- perl - Perl 字符串 if/或比较运算符
- c# - System.Runtime.InteropServices.SEHException C#,winforms
- r - 连续计数相同类型的值并省略中断
- ajax - 通过 Ajax 重新加载部分视图:部分中的控件被重命名
- r - 基于另一列计算一列的时间差
- java - 如何对使用 CountdownLatch 同步的异步代码进行单元测试
- python - 使用 Cloud Function 生成的新表创建/替换 Big Query 表
- java - 没有为 XSD 和 WSDL 文件生成 XMLBean 类 (Maven)
- c++ - 调用 send() 关闭应用程序而不会出错
- javascript - 使用 JS/JQuery 从附加的选择器选项中获取值