c++类的基类构造函数

在c++中子类构造时,会先调用基类的构造函数,可以利用此方法,将所有子类中共用的成员变量放入到基类的构造函数中进行初始化,如下代码

[php]
class B
{
public:
B()
{
printf("class B construct\n");
}
B(int a)
{
printf("class B construct a%d\n", a);
}
virtual ~B(){}
virtual int Add(int a, int b);
};

class C : public B
{
public:
C()
{
printf("class C construct\n");
}
C(int a)
{
printf("class C construct a%d\n", a);
}
virtual ~C(){}
virtual int Add(int a, int b);
};
int main()
{
B* b = new B;
B* c = new C(1);
int result = b->Add(1,2);
printf("result1:%d\n", result);
result = c->Add(1,2);
printf("result2:%d\n", result);
return 0;
}
[/php]

执行结果为:
[php]
class B construct
class B construct
class C construct a1
result1:3
result2:4
Press any key to continue
[/php]
可以看出,子类的构造前先执行基类的构造函数。

Comments are closed.