首页 > 解决方案 > 在没有成员函数的情况下重载一元减号运算符

问题描述

考虑以下程序:

//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。有人可以解释什么是错的吗?

标签: c++operator-overloading

解决方案


如果你想这样做,你test&不需要。 test你可能不应该;一元减号不应该改变它的参数,它应该返回一个修改过的参数。


推荐阅读