写在前面
初始化列表,旨在初始化的时候为属性赋值
码上建功
//先看一个最基本的构造函数,带初始化属性列表的
struct Person {
int m_age;
int m_height;
Person() {
this->m_age = 10; //初始化赋值,只能用this获得属性,this类似于OC中的self
this->m_height = 20;
}
void display() {
cout << "m_age is " << this->m_age << endl;
cout << "m_height is " << this->m_height << endl;
}
};
运行一下
Person person;
person.display();
看下打印结果:
m_age is 10
m_height is 20
//初始化的时候给属性赋值
struct Person {
int m_age;
int m_height;
// 初始化列表 :m_age(age), m_height(height)
//用一个冒号隔开,前面是需要传入的参数,后面是要赋值的属性
Person(int age, int height) :m_height(height), m_age(age) {
//对属性进行一些加工操作
}
void display() {
cout << "m_age is " << this->m_age << endl;
cout << "m_height is " << this->m_height << endl;
}
};
使用
Person person2(15, 25);
person2.display();
打印结果
m_age is 15
m_height is 25
当然在初始化的时候也可以通过函数调用返回初始化列表的值
int myAge() {
cout << "myAge()" << endl;
return 30;
}
int myHeight() {
cout << "myHeight()" << endl;
return 180;
}
struct Person {
int m_age;
int m_height;
// 初始化列表 :m_age(age), m_height(height)
//用一个冒号隔开,前面是需要传入的参数,后面是要赋值的属性
Person():m_height(myHeight()), m_age(myAge()) {
}
void display() {
cout << "m_age is " << this->m_age << endl;
cout << "m_height is " << this->m_height << endl;
}
};
调用
Person person;
person.display();
打印结果:
myAge()
myHeight()
m_age is 30
m_height is 180
当然你也可以这样来初始化
struct Person {
int m_age;
int m_height;
Person(int age, int height) {
cout << "Person(int age, int height) " << this << endl;
this->m_age = age;
this->m_height = height;
}
void display() {
cout << "m_age is " << this->m_age << endl;
cout << "m_height is " << this->m_height << endl;
}
};
调用
Person person2(15, 25);
person2.display();
打印
m_age is 15
m_height is 25
## 多个初始化列表方法时
struct Person {
int m_age;
int m_height;
Person() :Person(0, 0) { }
Person(int age, int height) :m_age(age), m_height(height) { }
void display() {
cout << "m_age is " << this->m_age << endl;
cout << "m_height is " << this->m_height << endl;
}
};
调用:
Person person;
person.display();
Person person2(15, 25);
person2.display();
打印结果:
m_age is 0
m_height is 0
m_age is 15
m_height is 25
## 如果函数声明和实现是分离的
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) {
}
调用
Person person;
person.display();
Person person2(10);
person2.display();
Person person3(20, 180);
person3.display();
打印结果:
m_age is 0
m_height is 0
m_age is 10
m_height is 0
m_age is 20
m_height is 180
装逼一下
一种便捷的初始化成员变量的方式
只能用在构造函数中
初始化顺序只跟成员变量的声明顺序有关
◼ 如果函数声明和实现是分离的
初始化列表只能写在函数的实现中
默认参数只能写在函数的声明中
完整代码demo,请移步GitHub:DDGLearningCpp