2010-03-24 58 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