重载单目运算符以及重载运算符的注意事项

一、单目运算符的重载

单目运算符可分为两种:

1)可以放在前面,也可以放在后面的单目,如:++ -- 

2)只能放在前面的运算符:! +(正号) -(负号)&  ~   ()

3)只能放到后面的运算符:*  -> 

重载单目运算符方法有两种: 类成员重载以及友元函数重载。

具体形式如下:

 入参和返回值根据单目运算符的特性进行选择,导图只是一个通用形式,明白意思就行。

 上代码:

#include <QCoreApplication>
#include <iostream>
using namespace std;

class Interger
{
public:
    Interger(int d=0):m_nData(d){}

    void operator--(int)
    {
        this->m_nData--;
        cout<<m_nData<<endl;
        cout << "operator--(int)"<< endl;
    }

    void operator++(int)
    {
        this->m_nData++;
        cout<<m_nData<<endl;
        cout << "operator++(int)"<< endl;
    }

    void operator++()
    {
        this->m_nData = this->m_nData+2;
        cout<<m_nData<<endl;
        cout << "operator++()"<< endl;
    }

    void show()
    {
        cout<<m_nData<<endl;
    }
private:
    int m_nData;
public:
    friend ostream& operator<<(ostream& os, Interger& input );
    friend Interger& operator!(Interger& input);
};


ostream& operator<<(ostream& os, Interger& input )
{
    return os<<input.m_nData <<endl;
}

Interger& operator!(Interger& input)
{
    input.m_nData = !input.m_nData;
    cout << "operator!()"<< endl;
    cout<< input.m_nData <<endl;
    return  input;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Interger aa;
    aa--;
    ++aa;
    aa++;

    !aa;

    return a.exec();
}

运行结果

二、运算符重载重载注意事项:

1,以下运算符不能重载

        ?:  .   ::  sizeof   && || & |

2,不能发明运算符

       比如 @

3,不能改变运算符的特性,符合队形的运算属性。

4,不能重载基本类型的运算,重载时至少要有一个是类类型。

5,只能重载成全局运算符的运算符

        第一个操作数是C++预定义类型 <<   >>  ostream istream类型

        第一个操作数是基本类型

6,只能重载成成员函数的运算符

        1)=(+= -= *=)   ---- 赋值运算符

        2)[]  ---------------数组对象(把对象当数组用)

        3)() ----------------强转,函数对象(把对象当函数使用)

        4)-> *  -------------指针对象(把对象当指针使用) 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大余里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值