简体   繁体   中英

Overload dereference operator

I'm trying to overload the dereference operator, but compiling the following code results in the error '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;
}

What am I doing wrong?

You're dereferencing a pointer to X . Your class is OK (as far as it's implemented).

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

You should apply dereference operator to a class type. In your code x has a pointer type. Write the following:

int t = **x;

or

int t = x->operator*();

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

operator int() const { return 5; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM