2010-03-24 54 views
9

我想超載引用操作,但在編譯下面的代碼導致錯誤'initializing' : cannot convert from 'X' to 'int'超載引用操作

struct X { 
    void f() {} 
    int operator*() const { return 5; } 
}; 

int main() 
{ 
    X* x = new X; 
    int t = *x; 
    delete x; 
    return -898; 
} 

我在做什麼錯?

回答

14

您應該將解引用運算符應用於類類型。在你的代碼x有一個指針類型。編寫如下:

int t = **x; 

int t = x->operator*(); 
14

您正在廢除指向X的指針。你的課程沒問題(就實施而言)。

int main() 
{ 
    X x; // no pointer 
    int t = *x; // x acts like a pointer 
} 
1

如果你想在原來的代碼工作,你需要重載INT-轉換運算符爲你的類:

operator int() const { return 5; } 
+0

'運營商INT '有很多問題,最好避免。解引用運算符可以用作指針仿真。 – Potatoswatter 2010-03-24 07:59:40

+0

@David:轉換爲'bool'的人比其他人多一個人,但也許這是一個下降; v) – Potatoswatter 2010-03-24 08:05:55

+0

@David:問題是關於'int operator *',而不是'operator int *' – visitor 2010-03-24 12:10:57