简体   繁体   中英

Can i make assignment operator to work like copy constructor?

Hello i got a class which looks like this:

class myClass{
public:
 //other consturctors

 //copy constructor:
 myClass (const myClass & x)
 : C1(x.C1), C2(x.C2), C3(x.C3), S1(x.S1) {};

 //other functions

 myClass & operator = (const myClass & x);

private:
 const otherClass1 C1;
 const otherClass2 C2;
 const otherClass3 * C3;
 string S1;
}

and I my problem is with assingment operator, because the compiler doesnt allow me to do it like in copy constructor. Thats problem because classes i need to assign doesnt have assign operator implemented and i cant edit them so I cant just do it like this:

myClass & operator = (const myClass & x) {
 C1=x.C1; // -> compile error
 C2=x.C2; // -> compile error
 C3=x.C3;
 S1=x.S1;
 return *this;
}

So I've tried to implement the assign operator like:

myClass & operator = (const myClass & x) {
 static myClass tmp(x);
 return tmp;
}

althoght its working a little bit, I think its causing some problems in my program especially inserting to vector of myClasses doesnt work very well.

Could you guys give me advice how to correctly make assign operator to work like I need ? (remove old myClass and make myClass(copy) istead of old one, or somehow assign classes with this syntax :C1(copy.C1) ... {} ) ?

EDIT: Removing const from C1 and C2 seems to be solution to my problem.

you have const data members so you can't change them in assignment operator. other noticeable thing is that you are doing shallow copy in your copy constructor, which you should avoid. you are only copying address in one pointer to another, it means both pointers will point to same address and if later on one deletes it, an other will become dangling pointer.

Forget about the 3rd piece of code with the static, you should try to get the second block of code working, and resolve the 2 compile errors.

If removing the constness does not work, you can store C1 and C2 on the heap.

const otherClass1 * C1;
const otherClass2 * C2;

Change them to pointers and new/delete them where needed, so you can use the copy constructor with a new, instead of the assignment operator (which you say does not exist for those classes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM