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 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*();
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
}
If you want the original code to work, you need to overload the int-cast operator for your class:
operator int() const { return 5; }
精彩评论