C++primer--拷貝控制__構造函數和析構函數的執行時期

這裏寫圖片描述

#include<iostream>
#include<vector>
using namespace std;
struct X
{
    X() { cout << "這裏是構造函數X()" << endl; }
    X(const X&) { cout << "這裏是拷貝構造函數" << endl; }
    X&operator =(const X&rhs) { cout << "這裏是拷貝賦值函數X&operator=(const X&rhs)" << endl; return *this; }
    ~X() { cout << "這裏是析構函數~X()" << endl; }
};
void testx1(X&x)
{

}
void textx2(X x)
{

}
int main(int argc, char ** argv)
{
    cout << "這裏是局部變量" << endl;
    X x;
    cout << endl;
    cout << "非引用傳參" << endl;
    textx2(x);
    cout << endl;
    cout << "引用傳參" << endl;
    testx1(x);
    cout << endl;

    cout << "動態分配" << endl;
    X*px = new X;
    cout << endl;

    cout << "將結構體變量添加到容器vector中" << endl;
    vector<X>getX;
    getX.push_back(x);
    cout << endl;

    cout << "釋放動態分配對象" << endl;
    delete px;
    cout << endl;

    cout << "間接初始化和賦值" << endl;
    X y = x;
    y = x;
    cout << endl;

    cout << "程序結束" << endl;
    system("pause");
    return 0;
}

本例主要說明了一個結構體的拷貝基本控制,以及析構的執行時期,幫助理解構造函數以及析構函數的意義。可以自己試着分析一下代碼的生成,然後試運行

運行結構如下:
這裏寫圖片描述

對於構造函數執行的時期再談

看代碼

#include<iostream>
#include<vector>
using namespace std;
class numeered
{
private:
    static int textnum;
public:
    numeered() { mysn = textnum++; }
    numeered(const numeered&n) { mysn = ++textnum; }
    int mysn;
};
int numeered::textnum = 0;
void print(const numeered &s)
{
    cout << s.mysn << endl;
}
int main()
{

    numeered a, b = a, c = b;
    print(a);
    print(b);
    print(c);
    system("pause");
    return 0;
}

如果只是簡單的沒有自定義構造函數的話,在定義類對象時進行的賦值操作會進行簡單的賦值操作,也就是會這裏的a,b,c的mysn值相同不發生改變但是,在進行輸出的時候,你輸出的時候,傳進去的類類型參數是numeered x就會在傳遞參數的時候進行參數默認構造,對傳進去的mysn值進行改變,而你在傳遞一個常引用類類型參數時,則不發生改變。上面的代碼例子,意在說明,是傳遞常量引用後的代碼,輸出值你可以與傳遞非常量引用的值比對,會發現是不一樣的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章