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