构造函数一般写法
class Person {
int m_age;
int m_height;
public:
Person() :Person(0, 0) {
}
Person(int age) :Person(age, 0) {
}
Person(int age, int height) :m_age(age), m_height(height) {
}
};
如果使用了默认参数,可以简写成一个构造函数
Person(int age = 0, int height = 0) :m_age(age), m_height(height) {
}
调用示例
int main() {
Person person;
Person person2(10);
Person person3(20, 180);
getchar();
return 0;
}
如果函数声明和实现是分离的
默认参数只能写在函数的声明中
Person(int age = 0, int height = 0);
初始化列表只能写在函数的实现中
Person::Person(int age, int height) :m_age(age), m_height(height) {
}
父类的构造函数
1.子类的构造函数默认会调用父类的无参构造函数
class Person {
int m_age;
public:
Person() {
cout << "Person()" << endl;
}
Person(int age) :m_age(age) {
cout << "Person(int age)" << endl;
}
};
class Student : public Person {
int m_score;
public:
Student() {
cout << "Student()" << endl;
}
Student(int age, int score) :m_score(score), Person(age) {
cout << "Student(int age, int score)" << endl;
}
};
2.如果子类的构造函数显式地调用了父类的有参构造函数,就不会再去默认调用父类的无参构造函数
3.如果父类缺少无参构造函数,子类的构造函数必须显式调用父类的有参构造函数
class Person {
int m_age;
public:
Person(int age) :m_age(age) {
cout << "Person(int age)" << endl;
}
};
class Student : public Person {
int m_score;
public:
Student() :Person(0) {
}
};
构造函数、析构函数顺序
构造函数和析构函数顺序相反
int main() {
Student student;
getchar();
return 0;
}
初始化子类student
构造函数调用顺序
Person() -> Student()
子类student
析构函数调用顺序
~Student()-> ~Person()