初始化列表特点
-
- 一种便捷的初始化成员变量的方式
- 2.只能用在构造函数中
- 3.初始化顺序只跟成员变量的声明顺序有关
构造函数
struct Person {
int m_age;
int m_height;
Person(int age, int height) {
this->m_age = age;
this->m_height = height;
}
};
等价于
struct Person {
int m_age;
int m_height;
Person(int age, int height) :m_height(height), m_age(m_height) {
}
};
#### 思考以下会打印成员变量值是多少
Person person2(10, 20);
person2.display();
int myAge() {
cout << "myAge()" << endl;
return 30;
}
int myHeight() {
cout << "myHeight()" << endl;
return 180;
}
Person(int age, int height) :m_height(myAge()), m_age(myHeight()) {
}
void display() {
cout << "m_age is " << this->m_age << endl;
cout << "m_height is " << this->m_height << endl;
}
构造函数的互相调用
构造函数调用构造函数,只能放在初始化列表调用(包括子类调用父类),其格式如下 调用示例
Person() :Person(0, 0) { }
Person(int age, int height) :m_age(age), m_height(height) { }
错误示例
Person() :Person(0, 0) {
cout << "Person() " << this << endl;
// 直接调用构造函数,会创建一个临时对象,传入一个临时的地址值给this指针
// Person(0, 0);
}
Person(int age, int height) {
cout << "Person(int age, int height) " << this << endl;
this->m_age = age;
this->m_height = height;
}