Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top