在CPP中,一个类的操作符有俩个作用。
- 第一是对这个类的对象进行操作,如比较,赋值,位移等;
- 第二是对这个类的对象进行隐式转换
一个例子的代码:
#include <iostream>
using namespace std;
struct struct_a{
int ta;
int tb;
};
class A
{
public:
A(int a) :_a(a) {cout<<"constructor"<<endl;}
// 1: operation
bool operator > (A aparam)
{
cout << "operator >" << endl;
return _a > aparam._a;
}
// 2: implicitly conversion
operator bool()
{
cout << "operator bool" << endl;
return _a;
}
operator struct_a ()
{
struct_a tobj;
tobj.ta = _a;
cout<<"operator ttt"<<endl;
return tobj;
}
public:
int _a;
};
int main()
{
A a(2);
A b(10);
cout<<"a>b ? : "<< (a>b) <<endl;
cout<<"b._a : "<<b._a<<" b : "<<b<<endl;
struct_a aStruct = a;
cout<<"aStruct.ta : "<<aStruct.ta<<endl;
return 0;
}
这段代码的运行结果是:
constructor
constructor
operator >
a>b ? : 0
operator bool
b._a : 10 b : 1
operator ttt
aStruct.ta : 2
在比较a>b时,就是调用的operator >, 返回的是bool值True或者False, 这就是对a和b进行比较操作,比较的对象是a和b中的公有变量_a, 具体操作可以通过更改> operator 改变。
在用cout把b的对象输出时, 会调用operator bool(), 把对象b转成bool类型了。
struct_a aStruct = a 时,调用operator struct_a, 把类A的对象a隐式的转为struct tobj, 并且赋值给aStruct。