拷贝构造函数发生在对象还没有创建,需要创建时

如:   MyClass obj1(1);  

            MyClassobj3 = obj1;

赋值操作符重载仅发生在对象已经执行过构造函数,即已经创建的情况下

如:

                 MyClass obj1(1);

                 MyClass obj3;

                obj3 = obj1;



具体代码如下:

class MyClass

{

public:

                MyClass( int i = 0)

                {

                                cout << i;

                }

                MyClass( const MyClass &x)

                {

                                cout << 2;

                }

                 MyClass &operator=(const MyClass & x)

                {

                                cout << 3;

                                 return *this ;

                }

                ~MyClass()

                {

                                cout << 4;

                }

};

int main()

{

                 MyClass obj1(1);

                 MyClass  obj2(2);

                 MyClass obj3;

                obj3 = obj1;

                 return 0;

}

输出:1203444

先创建对象obj1,调用构造函数并初始化为1,输出1

再创建对象obj2,调用构造函数并初始化为2,输出2

创建对象obj3,调用构造函数,使用默认值为0,输出0

obj1赋值给obj3时,调用赋值函数,输出3

再依次析构,析构的顺序和调用构造的顺序相反

先析构obj3,在析构obj2,最后析构obj1


class MyClass

{

public:

                MyClass( int i = 0)

                {

                                cout << i;

                }

                MyClass( const MyClass &x)

                {

                                cout << 2;

                }

                 MyClass &operator=(const MyClass & x)

                {

                                cout << 3;

                                 return *this ;

                }

                ~MyClass()

                {

                                cout << 4;

                }

};

int main()

{

                 MyClass obj1(1);

                 MyClass   obj2(2);

                 MyClass obj3 = obj1;

                 return 0;

}



输出:122444

依次创建对象obj1,obj2,调用两次构造,分别输出初始化的值1,2

MyClass obj3 = obj1;由于赋值的时候obj3还没有创建,所以会调用拷贝构造函数,输出2

再依次析构三个对象