重载解除引用运算符

big*_*g-z 9 c++ operator-overloading

我正在尝试重载dereference运算符,但编译以下代码会导致错误'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;
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Pot*_*ter 14

你正在取消引用一个指针X.你的课是好的(就其实施而言).

int main()
{
    X x; // no pointer
    int t = *x; // x acts like a pointer
}
Run Code Online (Sandbox Code Playgroud)


Kir*_*sky 14

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

int t = **x;
Run Code Online (Sandbox Code Playgroud)

要么

int t = x->operator*();
Run Code Online (Sandbox Code Playgroud)