C++ 回忆录8 copy constructor and Assigment Operator

来源:互联网 发布:淘宝查假冒伪劣处罚 编辑:程序博客网 时间:2024/05/19 18:12

1. 赋值,有两种方式,

int i=10;

int b=i;//copy assignment

int c(i); //direct assignment

这两方式虽然最终结果都是为一个变量赋值.但放声的过程不一样.  以类说明:

string a="abcdef";

string b("abcdef");

a,b 两个对象最后内容是一样的,但过程则不一样.

a, 首先是调用 string(const char * );的构造器创建一个string 对象,然后在调用copy constructor 把这个临时对象赋给a,

b 直接就是调用string(const char * );创建b.


对于non reference 的parameter ,return value,这里面的参数的初始化, 函数返回的值得,都要用到这个copy constructor.


2.define copy constructor

class A

{

   public:

   A(const A &);

  private int m_int;

}

A::A(const A & org):m_int(org.m_int)  //一般都是将这个赋值放在初始化列表中做.

{

}

3.prevent copy assigment/

有的对象不允许copy assigment,这时候就要将copy constructor 声明为private.定义可以不做任何事情.

但尝试做copy assigment 时候,编译器会报错.

此时就可以通过引用进行赋值,但其实是同一个对象的别名而已.没涉及到对象的另外创建.


4.container & array initialize

容器对象(sequential container)的初始化也是要调用copy constructor ,so the best pratice is to init the size to value,then add the element if need

vector<string> seve(5);// first using the string default constructor to  creat the temporaly obj then use the copy constructor to copy  the tmp obj to the container.


Sale_itme [6];//如果没有{XX}的初始化块,则调用默认的constructor   to initialize each element

Sale_item[]={string("adf"),Sale_item()}; //if specify the intialize {} ,the will  after obj creat will  use copy constructor to initizlize the array element.


5. Assigment operator =

= 赋值运算符也是可以重载,事实上如果我们不重载=, just like copy constructor ,the compile will sysnthesize one for us.


= 赋值运算符重载,其实跟函数差不多. 函数名称就是operator= ,就是关键字operator 跟= 组成函数名称.

参数列表其实就是跟该运算符的操作数是一致的,从左到右. 如=. 第一个参数就是左边的对象,由于已经有implict this ,so 第一个参数被ommit. 所以函数的第一个参数就是第二个操作数了.


class Student

{

  int m_age;

 string m_name;

 Student(Student &); //copy constructor

Studnet & operator=(const Student & secondOperand );

};

Student & Student::operator=(const Student & so)

{

 XXX some operation

   return *this;

}


main...

Student org;

Student st2=org;  //声明时候就初始化, will call the copy constructor ,but will not call the assigment operatror overload function

Student st3;

st3=org; // in thi situation ,will just call the assiment operator function,but not call the copy constructor.







原创粉丝点击