c++使用初始化列表來初始化字段


#include<iostream>
using namespace std;

class Student1
{
private:
	int _a;
    int _b;

public:
    void
    fprint()
    {
        cout << " a = " << _a << " " << "b = " << _b << endl;
    }

    //Student1(int i):b(i),a(b){ }    //異常順序:發現a的值為0  b的值為2  說明初始化僅僅對b有效果,對a沒有起到初始化作用
    
	Student1(int a, int b): _a(a), _b(b) 
	{ 
		cout << "constructor" << endl;
	} //正常順序:發現a = b = 2 說明兩個變量都是初始化了的

    Student1()                         // 無參構造函數
    {
        cout << "默認構造函數Student1" << endl ;
    }

    Student1(const Student1 &t1) //拷貝構造函數
    {
        cout << "拷貝構造函數Student1" << endl ;
        this->_a = t1._a;
		this->_b = t1._b;
    }

    Student1 &
    operator = (const Student1 &t1) // 賦值運算符
    {
        cout << "賦值函數Student1" << endl ;
        this->_a = t1._a ;
		this->_b = t1._b ;
        return *this;
    }

};

class Teacher
{
public:
    Student1 test;	//類中包含類
    Teacher(Student1 &t1)
    {
        test  = t1 ;
    }
};

int main(void)
{
    Student1 A(2,4);      //進入默認構造函數
    Teacher B(A);        //進入拷貝構造函數
    A.fprint();           //輸出前面初始化的結果
	B.test.fprint();
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM