初始化列表,用来初始化成员变量的
Person(int age,int height) :m_age(age), m_height(height) {} //m_age = age m_height = height
初始化列表,只能放到实现里面
struct Person {
int m_age;
int m_height;
Person(int age = 0, int height = 0);
};
Person::Person(int age, int height) :m_age(age), m_height(height) {} //这个只能放实现
构造函数的互相调用
struct Person {
int m_age;
int m_height;
Person () : Person(0, 0){ //调用有参的构造函数,只能放这里
}
Person(int age, int height) {
m_age = age;
m_height = height;
}
};
子类的构造函数默认会调用父类的无参构造函数
struct Person {
int m_age;
Person () {
cout << "Person::Person()" << endl;
}
};
struct student : Person {
int m_no;
Student() {
cout << "Student::Student()" << endl;
}
};
int main() {
Student student; //默认还会调用父类的 Person()函数
}
子类的构造函数显示地调用了父类的有参构造函数,就不会再去默认调用父类的无参构造函数
Student() : Person(10) { ...} /调用父类的有参构造函数写冒号后面
构造与析构顺序
struct Student : Person {
Student() {
// call Person::Person 先调用父类的构造
cout << "Student::Student()" << endl;
}
~Student() {
cout << "Student::~Student()" << endl;
// call Person::~Person 后调用父类的析构
}
};