使用operator[]和operator=
给定一个重载“[]”运算符的简单类:
class A
{
public:
int operator[](int p_index)
{
return a[p_index];
}
private:
int a[5];
};
我想完成以下任务:
void main()
{
A Aobject;
Aobject[0] = 1; // Problem here
}
在这种情况下如何重载赋值“=”运算符以与“[]”运算符一起使用?
Given a simple class that overloads the '[ ]' operator:
class A
{
public:
int operator[](int p_index)
{
return a[p_index];
}
private:
int a[5];
};
I would like to accomplish the following:
void main()
{
A Aobject;
Aobject[0] = 1; // Problem here
}
How can I overload the assignment '=' operator in this case to work with the '[ ]' operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不会重载
=
运算符。您返回一个参考。确保还提供
const
版本:You don't overload the
=
operator. You return a reference.Make sure to provide a
const
version as well:让它返回一个引用:
请注意,您还需要一个 const 版本,它确实返回一个值:
Make it return a reference:
Note that you will also want a const version, which does return a value:
这里的问题是您返回的是可用 a 中包含的值。
在 main 中,您尝试分配不可用的 int 变量。
您可能会看到这样的编译错误“错误 C2106:'=':左操作数必须是左值”。
意味着不能将值分配给不可用的变量。
请将运算符[]重载函数的返回类型更改为引用或指针,这样就可以正常工作。
The problem here is you are returning the value which is contained in vaiable a.
In main you are trying to assign int variable which is not available.
You would have seen compilation error "error C2106: '=' : left operand must be l-value" like this.
Means the value cannot be assigned to a variable which is not available.
Please change return type of operator [] overloading function into reference or pointer it will work fine.