重载解除引用运算符

时间:2010-03-24 07:52:30

标签: c++ operator-overloading

我正在尝试重载取消引用运算符,但是编译以下代码会导致错误'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;
}

我做错了什么?

3 个答案:

答案 0 :(得分:14)

您正在取消引用指向X的指针。你的课程没问题(就其实施而言)。

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

答案 1 :(得分:14)

您应该将取消引用运算符应用于类类型。在您的代码x中有一个指针类型。写下以下内容:

int t = **x;

int t = x->operator*();

答案 2 :(得分:1)

如果您希望原始代码有效,则需要为您的类重载int-cast运算符:

operator int() const { return 5; }
相关问题