級聯類型轉換時,如何獲得類型轉換才能工作?C++級聯類型轉換
下面的代碼應該很簡單,但是從TypeB到int的轉換需要編譯器自動推導出兩種類型的轉換。但事實並非如此。
我不能簡單地實現 operator int()const {return val; } TypeB類,因爲這應該是一個模板類我不知道要轉換爲哪種類型。
class TypeA {
public:
TypeA(int a) : val(a) {}
operator int() const { return val; }
private:
int val;
};
class TypeB {
public:
TypeB(TypeA a) : val(a) {}
operator TypeA() const { return val; }
// operator int() const { return val; } // Explicit conversion to int which I can not know.
private:
TypeA val;
};
void main() {
TypeA a = 9;
TypeB b = a;
int int_a = a;
TypeA a2 = b;
int int_b = b; // Compilation error:
// No suitable conversion function from 'TypeB' to 'int' exists
}
問候