#include<iostream>
using namespace std;
class A
{
public:
int a;
A();
};
A::A()
{
cout << "A constructor" << endl;
}
class B
{
public:
int b;
B();
};
B::B()
{
cout << "B constructor" << endl;
}
class C
{
public:
A a;
B b;
int c;
C();
};
C::C():c(1)
{
cout << a.a << b.b << c << endl;
}
int main()
{
C c;
}
输出为
A constructor
B constructor
一串数字
即当C的对象c被创建时,A a、B b分别分配空间后先分别进入他们的constructor,而后c对象创建完成后再进入c的constructor。
class A
{
public:
int a;
A(int i);
};
A::A(int i)
{
a = i;
cout << "A constructor" << endl;
}
class B
{
public:
int b;
B(int i);
};
B::B(int i)
{
b = i;
cout << "B constructor" << endl;
}
class C
{
public:
int c;
C();
private:
A a;
B b;
};
C::C():c(1)
{
cout << c << endl;
}
如果把类C改为这样, 即初始化列表里没有初始化a和b,而class A和class B都没有default constructor(因为上面A、B类的constructor带参数了),这样在对象c被创建时不会自动调用a和b的constructor,编译报错。