码迷,mamicode.com
首页 > 其他好文 > 详细

一元运算符重载

时间:2019-08-08 19:32:42      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:运算符   重载   display   --   cout   end   一个   逻辑   using   

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

  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

一元运算符重载

标签:运算符   重载   display   --   cout   end   一个   逻辑   using   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!