#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();
}