C++ 重载运算符 operator
生活随笔
收集整理的這篇文章主要介紹了
C++ 重载运算符 operator
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
operator? 是什么
operator 是C++的一個(gè)關(guān)鍵字,它和運(yùn)算符(+,-,*,/,=,等等)一起使用,表示一個(gè)運(yùn)算符重載函數(shù)
operator 沒有返回語句
operator 的作用 :
1?把對(duì)象當(dāng)函數(shù)使用
具體的如下:
#include <iostream>
#include <string>
using namespace std;
class People
{
public:// 把對(duì)象當(dāng)函數(shù)使用int operator()(int a, int b) const{return a + b;}
};int main()
{People p;cout << p(13, 15) << endl;return 0;
}
2 對(duì)象進(jìn)行計(jì)算
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 類型轉(zhuǎn)換
#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;
}
總結(jié)
以上是生活随笔為你收集整理的C++ 重载运算符 operator的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剑灵昆仑武器升级到泰天15段划算还是从泰
- 下一篇: C++ 复制构造函数或者拷贝构造函数