C++ 重载运算符 operator

operator  是什么

operator 是C++的一个关键字,它和运算符(+,-,*,/,=,等等)一起使用,表示一个运算符重载函数

operator 没有返回语句

operator 的作用 :

1 把对象当函数使用

具体的如下:

#include <iostream>
#include <string>
using namespace std;
class People
{
public:
    // 把对象当函数使用
    int operator()(int a, int b) const
    {
        return a + b;
    }
};

int main()
{
    People p;
    cout << p(13, 15) << endl;
    return 0;
}

2 对象进行计算

operator的操作符有很多,如下

具体代码如下:

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

class People
{

public:
    int mage;

public:
    People(int age)
    {
        mage = age;
    }

    People operator+(People p)
    {
        return People(mage + p.mage);
    }

    void showMessage()
    {
        cout << mage << endl;
    }
};

int main()
{
    People people1(18);
    People people2(20);
    People people3(0);
    people3 = people1 + people2;
    people3.showMessage();
    return 0;
}

 3 类型转换

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

class People
{

public:
    int height;

public:
    People(double mheight =0){
        height  = mheight;
    };
    
   operator double()
    {
        return height;
    }

};


int main()
{
    People people1(175.5);
    People people2(180.3);
    People people3(0);
    people3 = people1 + people2;
    cout<<people3<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值