注:本文測試實例使用的編譯器版本爲clang-703.0.29。小程序
咱們已經習慣了基本數據類型的顯式或隱示轉換,如:測試
int a = 10; float f = (float)a;
float c = a;
其實經過operator的使用,class也能夠達到任意類型的顯式或隱式轉換的效果,如:spa
#include <cstdlib> #include <cstdio> using namespace std; struct A { char a; }; class B { public: char b; }; class C { private: A _a; B _b; public: char c; operator A() { return _a; } operator B() { return _b; } }; int main() { C c; c.c = 'c'; A a1 = (A)c; A a2 = c; B b1 = (B)c; B b2 = c; a1.a = 'a'; a2.a = 'a'; b1.b = 'b'; b2.b = 'b'; printf("a1.a: %c\na2.a: %c\nb1.b: %c\nb2.b: %c\nc.c: %c\n", a1.a, a2.a, b1.b, b2.b, c.c); return 0; }
上面這段小程序的輸出結果爲:code
a1.a: a
a2.a: a
b1.b: b
b2.b: b
c.c: c