一个简单的类赋值函数问题
我写了一个类
struct opera{
int a,b;
int op;
opera(int a1=0,int b1=0,int op1=-1):a(a1),b(b1),op(op1){}
opera& operator=(opera& tmp){
a=tmp.a;
b=tmp.b;
op=tmp.op;
}
,我想将它分配给一个数组元素,如下所示:
ans[a][b]= opera(t.a,t.b,i);
为什么它无法成功编译。
然而这可以工作:
opera tmp=opera(t.a,t.b,i);
ans[a][b]= tmp;
当然,struct opera不需要显式的赋值函数,
ans[a][b]= opera(t.a,t.b,i);
可以直接工作。
I write a class
struct opera{
int a,b;
int op;
opera(int a1=0,int b1=0,int op1=-1):a(a1),b(b1),op(op1){}
opera& operator=(opera& tmp){
a=tmp.a;
b=tmp.b;
op=tmp.op;
}
And I want to assign it to an array element like this:
ans[a][b]= opera(t.a,t.b,i);
Why it can't compile successfully.
However this can work:
opera tmp=opera(t.a,t.b,i);
ans[a][b]= tmp;
Of course,the struct opera don't need a explicit assignment function, and
ans[a][b]= opera(t.a,t.b,i);
can work directly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您想从临时对象进行分配时,您需要
另一行
是新对象的初始化,而不是分配。
When you want to assign from a temporary, you need
The other line
is an initialization of a new object, and not an assignment.
这会调用赋值运算符,这就是它无法编译的原因,因为从
opera(ta,tb,i)
创建的临时对象无法绑定到赋值运算符参数中的非常量引用。您需要做的就是:That invokes assignment operator that is why it cannot compile because the temporary object created out of
opera(t.a,t.b,i)
cannot be bound to the non-const reference in the assignment operator's parameter. All you need to do is this:这是因为您的复制构造函数/赋值运算符没有通过 const 引用获取其参数。否则,当您使用
ans[i][j]=opera(a,b,c);
时,会创建一个临时对象,并且根据 C++ 标准,您不能使用非常量引用这个物体。因此,您需要使用opera(const opera& o);That is because your copy ctor/assignment operator is not taking its parameter by const reference. Otherwise when you use
ans[i][j]=opera(a,b,c);
a temporary object is created, and according to C++ standard, you can not take a non-const reference for this object. Hence you need to useopera(const opera& o);