【问题】类类型是否能够类型转换到普通类型?
语法规则:
operator Type () { Type ret; // ... return ret; }类型转换函数:
与构造函数具有同等的地位使得编译器有能力将对象转化为其他类型编译器能够隐式的使用类型转换函数【注意】编译器会尽力尝试让源码通过编译。
Test t(1); int i = t;t这个对象为Test类型,怎么可能用于初始化int类型的变量呢!现在就报错吗?不急,我看看有没有类型转换函数!Ok,发现Test类中定义了operator int(),可以进行转换。
【范例代码】类类型转成基本类型
#include <iostream> #include <string> using namespace std; class Test { int mValue; public: Test(int i = 0) { mValue = i; } int value() { return mValue; } operator int () { return mValue; } }; int main(int argc, const char* argv[]) { Test t(100); int i = t; cout << "t.value() = " << t.value() << endl; cout << "i = " << i << endl; return 0; } 【问题】类类型之间的相互转换?【范例代码】类类型之间的转换
#include <iostream> #include <string> using namespace std; class Test; class Value { public: Value() { } explicit Value(Test& t) { } }; class Test { int mValue; public: Test(int i = 0) { mValue = i; } int value() { return mValue; } operator Value() { Value ret; cout << "operator Value()" << endl; return ret; } }; int main(int argc, const char* argv[]) { Test t(100); Value v = t; return 0; } 无法抑制隐式的类型转换函数调用类型转换函数可能与转换构造函数冲突工程中以Type toType()的公有成员代替类型转换函数