成员对象以其在类中声明的顺序构造,不以构造函数中构造参数表的顺序来规定对象的构造顺序。
//---------main.cpp------------
#include <iostream>
//测试成员对象的创建顺序
using namespace std;
class A
{
public:
A(int x){std::cout<<"A: "<<x<<"->";}
};
class B
{
public:
B(int x){std::cout<<"B: "<<x<<"->";}
};
class C
{
private:
A a;
B b;
public:
C(int x,int y):b(x),a(y){std::cout<<"c\n";}
};
int main(int argc,char **argv)
{
C c(15,9);
return 0;
}
A: 9->B: 15->c
请按任意键继续. . .
class C按 A、B的顺序定义对象成员,其构造函数又按b、a的顺序进行构造。到底听谁的呢?以定义顺序说了算。
1