C++重载单目运算符

单目运算符重载函数不需要参数,因为相当于是对自己对象的操作,没有涉及2个以上的对象。

以下实例以‘-’为测试

#include <iostream>
using namespace std;
class test
{
public:
    test(int a, int b) :a1(a), b1(b) {}
    test operator -()                                //重载单目运算符‘-’
    {
        a1 = a1*2;
        b1 = b1*2;
        return test(a1,b1);
    }
    void show()
    {
        cout << a1 <<" "<< b1 << endl;
    }
private:
    int a1;
    int b1;
};
int main()
{
    test t1(1, 2);
    -t1;
    t1.show();
    system("pause");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/god-for-speed/p/10842903.html