成员初始化表的执行顺序与速写顺序无关
首先给出结论,c++的成员初始化表的初始化,顺序与没有关系,有关系的是构造函数中,变量书写的顺序,越上面的越先初始化。
演示代码:
#include<bits/stdc++.h> using namespace std; class Student { int age; int year; int birthYear; public:Student(int,int); }; Student::Student(int x ,int y): year(x), birthYear(y),age(year - birthYear) { cout<<"age = "<<age<<endl; cout<<"year = "<<year<<endl; cout<<"birthYear = "<<birthYear<<endl; /* age = 0 // 运行结果age这里为0,因为按照构造函数的顺序, // age在上面,应该是age先初始化,所以age(year-birthYear)先运行, // 但是这个时候,year,birthYear都还没有初始化,默认为0,所以age最后为0 year = 2014 birthYear = 1976 */ } int main() { Student* p = new Student (2014,1976); delete p; return 0; }
正确写法:
#include<bits/stdc++.h> using namespace std; class Student { int year; int birthYear; int age; public:Student(int,int); }; Student::Student(int x ,int y): year(x), birthYear(y),age(year - birthYear) { cout<<"age = "<<age<<endl; cout<<"year = "<<year<<endl; cout<<"birthYear = "<<birthYear<<endl; } int main() { Student* p = new Student (2014,1976); delete p; return 0; }