Reputation: 987
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.
Upvotes: 1
Views: 135
Reputation: 73443
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);
Upvotes: 0
Reputation: 361402
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
Upvotes: 2
Reputation: 92261
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.
Upvotes: 5