简体   繁体   English

重载没有成员的一元减运算符 function

[英]Overloading unary minus operator without member function

Consider the following program:考虑以下程序:

//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;
}

On executing, this prints 7 instead of -7 on online compilers as well as Visual Studio Code on machine.在执行时,这会在在线编译器和机器上的 Visual Studio Code 上打印 7 而不是 -7。 Can someone explain what's wrong?有人可以解释出什么问题了吗?

You need test& not test if you want to do that.如果你想这样做,你需要test&而不是test You probably shouldn't;你可能不应该; unary minus shouldn't mutate its argument, it should return a modified one.一元减号不应该改变它的参数,它应该返回一个修改后的参数。

Consider the following program:考虑以下程序:

//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;
}

On executing, this prints 7 instead of -7 on online compilers as well as Visual Studio Code on machine.在执行时,这会在在线编译器和机器上的 Visual Studio Code 上打印 7 而不是 -7。 Can someone explain what's wrong?有人可以解释什么是错的吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM