c++ - Can i make assignment operator to work like copy constructor? -


hello got class looks 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 problem assingment operator, because compiler doesnt allow me in copy constructor. thats problem because classes need assign doesnt have assign operator implemented , cant edit them cant 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 implement assign operator like:

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

althoght working little bit, think causing problems in program inserting vector of myclasses doesnt work well.

could guys give me advice how correctly make assign operator work need ? (remove old myclass , make myclass(copy) istead of old one, or somehow assign classes syntax :c1(copy.c1) ... {} ) ?

edit: removing const c1 , c2 seems solution problem.

forget 3rd piece of code static, should try second block of code working, , resolve 2 compile errors.

if removing constness not work, can store c1 , c2 on heap.

const otherclass1 * c1; const otherclass2 * c2; 

change them pointers , new/delete them needed, can use copy constructor new, instead of assignment operator (which not exist classes)


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -