operator可以作为类转换函数或在类中作重载运行符下面对此两种使用场景进行描述
1、operator作类的转换函数
cpp
#include <iostream>
using namespace std;
class my_class
{
public:
operator int()//定义了一个将类转化为int的转换函数
{
return 1;
}
};
int main()
{
my_class a;
int i_a = (int)a;//显式的转换
cout <<"i_a:"<< i_a << endl;
cout <<"a:"<< a << endl;//隐式的转换
return 0;
}
运行结果
cpp
i_a:1
a:1
2、operator在类中重载运算符
cpp
#include <iostream>
using namespace std;
class DemoClass
{
public:
DemoClass() {}
DemoClass(int a, double b):a_(a),b_(b){}
~DemoClass(){}
int get_a() { return a_; }
double get_b() { return b_; }
DemoClass operator+(const DemoClass &adder) const//以成员函数方式重载+
{
DemoClass sum;
sum.a_ = a_ + adder.a_;
sum.b_ = b_ + adder.b_;
return sum;
}
friend DemoClass operator-(const DemoClass &A,const DemoClass &B)//以友元方式重载-
{
DemoClass diff;
diff.a_ = A.a_ - B.a_;
diff.b_ = A.b_ - B.b_;
return diff;
}
private:
int a_;
double b_;
};
int main()
{
DemoClass A(1, 1.1);
DemoClass B(2, 2.2);
DemoClass sum = A + B;
DemoClass diff = A - B;
cout <<"A+B:"<< sum.get_a() << " " << sum.get_b() << endl;
cout <<"A-B:"<<diff.get_a() << " " << diff.get_b() << endl;
return 0;
}
运行结果
cpp
A+B:3 3.3
A-B:-1 -1.1