一元运算符重载

一元运算符只对一个操作数进行操作,下面是一元运算符实例:

  1. 递增运算符(++) 和递减运算符(--)
  2. 一元减运算符,即符号(-)
  3. 逻辑非运算符(!)
/***
overone.cpp
***/
#include<iostream>
using namespace std;

class Distance
{
    private:
        int feet;
        int inches;
    public:
        Distance()
        {
            feet = 0;
            inches = 0;
        }
        Distance(int f,int i)
        {
            feet = f;
            inches = i;
        }

        void displayDistance()
        {
            cout << "F: " << feet << " I: " << inches << endl; 
        }

        Distance operator- ()
        {
            feet = -feet;
            inches = -inches;
            return Distance(feet,inches);
        }
};

int main()
{
    Distance D1(11,10), D2(-5,11);

    -D1;
    D1.displayDistance();

    -D2;
    D2.displayDistance();

    return 0;
}

运算结果:

exbot@ubuntu:~/wangqinghe/C++/20190808$ g++ overone.cpp -o overone

exbot@ubuntu:~/wangqinghe/C++/20190808$ ./overone

F: -11 I: -10

F: 5 I: -11

原文地址:https://www.cnblogs.com/wanghao-boke/p/11319647.html