C++中賦值函數和拷貝構造函數(舉例說明)

拷貝構造函數發生在對象尚未建立,須要建立時ide

如:   MyClass obj1(1);  函數

            MyClassobj3 = obj1;this

賦值操做符重載僅發生在對象已經執行過構造函數,即已經建立的狀況下spa

如:對象

                 MyClass obj1(1);it

                 MyClass obj3;class

                obj3 = obj1;構造函數



具體代碼以下:im

class MyClassdi

{

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

再依次析構三個對象

相關文章
相關標籤/搜索