這是所謂的用戶定義的轉換或UDC。它們允許您通過構造函數或特殊轉換函數指定轉換爲其他類型。
的語法如下:
operator <some_type_here>();
所以你的具體情況是一個轉換操作符的類型。
有你的編碼時,應該記住一些事情的:
- 一個UDC絕不能含糊,否則它將不會被調用
編譯器只能使用UDC隱式轉換單個對象在一個時間,所以鏈接的隱式轉換不起作用:
class A
{
int x;
public:
operator int() { return x; };
};
class B
{
A y;
public:
operator A() { return y; };
};
int main()
{
B obj_b;
int i = obj_b;//will fail, because it requires two implicit conversions: A->B->int
int j = A(obj_b);//will work, because the A->B conversion is explicit, and only B->int is implicit.
}
在派生類A轉換功能不隱藏在基類的變換函數,除非它們共轉變爲相同的類型。
通過建築師轉換時,只能使用默認轉換。例如:
class A
{
A(){}
A(int){}
}
int main()
{
A obj1 = 15.6;//will work, because float->int is a standart conversion
A obj2 = "Hello world!";//will not work, you'll have to define a cunstructor that takes a string.
}
你可以找到更多的信息here,here或here。