C++的拷贝构造函数

http://blog.csdn.net/lwbeyond/article/details/6202256

 

class X{

public:

X(const X& x) { cout << "copy constructor" << endl; }

 

 

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

http://www.cnblogs.com/whyandinside/archive/2012/05/12/2497237.html

拷贝构造函数与赋值运算符

行为很类似,但是应用的场合并不一样。拷贝构造函数应用于如下情况:

  • 对象以传值的方式作为一个函数的参数;
  • 对象以传值的方式作为一个函数的返回值;
  • 对象以另一个对象进行初始化

赋值运算符在上述情况都不能用,它只能用于对象初始化完成后,赋值时使用。下面是例子,注意=的时候:并不是所有使用=的地方都是赋值运算符:

 

复制代码
#include <iostream>

using namespace std;

class Sample
{
public:
    Sample(){};
    Sample(Sample & s)
    {
        cout<<"copy constructor"<<endl;
    }
    Sample & operator=(Sample &s)
    {
        cout<<"= operator"<<endl;
        return *this;
    }
};
void foo(Sample s){}
Sample doo()
{
    Sample s;
    return s;
}
int main(int argc, char ** argv)
{
    Sample s1;
    Sample s2(s1);//copy constructor
    Sample s3 = s1;//copy constructor

    Sample s4;
    s4 = s1; //= operator

    foo(s4);//copy constructor
    doo();//copy constructor
    return 0;
}
复制代码
posted @ 2015-09-14 15:31  forwardslash  阅读(97)  评论(0)    收藏  举报