Copy control: copying configuration, the assignment operator

the difference

Call the copy constructor

Teacher t2 = t1;    //类类型,复制初始化时调用拷贝构造函数,直接初始化调用对应构造函数

Call the assignment operator

Teacher t2;
t2 = t1;

Copy constructor

Single parameter, and the parameter type is a reference type of the class (modified constant const) constructor

class Test{
public:
  Test(){
    data = 0;
  }
  Test(int d):data(d){
  }
  ~Test(){
  }

  Test(const Test &test)
   {
    data = test.data;
  }
private:
  int data;
};

If the parameter as reference, copy constructor call

void func(const string &s1);    //隐式调用string拷贝构造

Assignment operator

class Test{
public:
  Test(){
    data = 0;
  }
  Test(int d):data(d){
  }
  ~Test(){
  }

  //重载=号运算符                                            
  Test& operator= (const Test &t){
    if(this != &t){    //防止自赋值
      data = t.data;
    }
    return *this;
  }
private:
  int data;
};

Prohibit copy

Private copy constructor and assignment operator

class Test{
public:
  Test(){
    data = 0;
  }
  Test(int d):data(d){
  }
  ~Test(){
  }
private:
  //  禁止拷贝                                         
  Test& operator= (const Test &);
  Test(const Test&);
  int data;
};

Guess you like

Origin www.cnblogs.com/xiongyungang/p/11361438.html
Recommended