随手写的程序:
class A
{
public:
A():a(b),b(1)
{
cout<<a<<endl ;
cout<<b<<endl ;
}
private:
int a,b;
};
int _tmain(int argc, _TCHAR* argv[])
{
A a ;
system("pause");
return 0;
}
输出结果为:
a为一个极大负数,b为1
修改下代码:
class A
{
public:
A():a(b),b(1)
{
cout<<a<<endl ;
cout<<b<<endl ;
}
private:
int b,a;
};
int _tmain(int argc, _TCHAR* argv[])
{
A a ;
system("pause");
return 0;
}
输出结果为:
a为1,b为1
两段代码唯一不同在于:int a,b修改成了int b,a;也就是前者先执行a(b)再执行b(1),后者先执行b(1),再执行a(b)
请记住一条准则:初始化列表中初始化顺序和它们在类中声明的顺序保持一致