在C++中有一个特殊的运算符重载方法--类型转换运算符重载,形如:operator type();
Code
class CDemo{
public:
CDemo(int x,int y){
this->_x = x;
this->_y = y;
}
operator int(){ // 运算符重载
return _x;
}
private:
int _x;
int _y;
};
Code
int _tmain(int argc, _TCHAR* argv[])
{
CDemo demo(10,30);
cout<<demo<<endl;
return 0;
}
运行结果:10
即_x的值,int()对demo进行了隐式类型转换。如果去除重载函数,则报error:二进制“<<”: 没有找到接受“CDemo”类型的右操作数的运算符(或没有可接受的转换).说明<<在遇到无法接受的类型时,会努力找到使之运行
的转换,直到失败。
Code
class CDemo{
public:
CDemo(int x,int y){
this->_x = x;
this->_y = y;
}
operator int(){ // 运算符重载
return _x;
}
private:
int _x;
int _y;
};
Code
int _tmain(int argc, _TCHAR* argv[])
{
CDemo demo(10,30);
cout<<demo<<endl;
return 0;
}
运行结果:10
即_x的值,int()对demo进行了隐式类型转换。如果去除重载函数,则报error:二进制“<<”: 没有找到接受“CDemo”类型的右操作数的运算符(或没有可接受的转换).说明<<在遇到无法接受的类型时,会努力找到使之运行
的转换,直到失败。