重载解引用运算符
我试图重载取消引用运算符,但编译以下代码会导致错误 'initializing' :无法从 'X' 转换为 'int'
:
struct X {
void f() {}
int operator*() const { return 5; }
};
int main()
{
X* x = new X;
int t = *x;
delete x;
return -898;
}
我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该将解引用运算符应用于类类型。在您的代码中
x
有一个指针类型。写下以下内容:或
You should apply dereference operator to a class type. In your code
x
has a pointer type. Write the following:or
您正在取消引用指向
X
的指针。你的课程没问题(就其实施而言)。You're dereferencing a pointer to
X
. Your class is OK (as far as it's implemented).如果您希望原始代码起作用,您需要为您的类重载 int-cast 运算符:
If you want the original code to work, you need to overload the int-cast operator for your class: