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;
}