开发者

A easy question of assignment function of class

开发者 https://www.devze.com 2023-03-05 05:13 出处:网络
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){

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;
  开发者_如何学Python  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.


When you want to assign from a temporary, you need

  opera& operator=(opera const& tmp){

The other line

opera tmp=opera(t.a,t.b,i);

is an initialization of a new object, and not an assignment.


ans[a][b]= opera(t.a,t.b,i);

Why it can't compile successfully.

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:

 opera& operator=(const opera & tmp)
                //^^^^ note this


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 use opera(const opera& o);

0

精彩评论

暂无评论...
验证码 换一张
取 消