
C++中的RAII机制指明”对象创建时通过构造函数进行初始化,析构时通过析构函数释放资源”,但实际中因类无构造函数时编译器将自动合成一个默认构造函数,该构造函数只服务于自身编译器构造需要而不负责对象成员构造,如这个实例中对象A成员val,next均未进行初始化,而对象B由于是类对象则调用其默认构造函数。但全局对象,静态对象编译器则自动进行将其初始化为0.
#include <iostream> using namespace std; class X {
public:
virtual void out() {
cout << "class X" << endl;
}
}; class B :public X{
public:
int i;
~B()
{
cout << "~B()" << endl;
} virtual void out() {
cout << "class B" << endl;
}
}; class A :public X{
public:
int val;
A *next;
B b;
virtual void out() {
cout << "class A" << endl;
}
}; class C:public X {
X *px;
public:
C():px(new A()) {
px->out();
}
~C() {
delete px;
cout << "~C()" << endl;
}
}; A b;
static A c;
int main(int argc, char *argv[]) { A a; C d;
//d.C::C();
cout << a.val << ",next:" << a.next << ",i:" << a.b.i<< endl;
cout << b.val << ",next:" << b.next << ",i:" << b.b.i << endl;
cout << c.val << ",next:" << c.next << ",i:" << c.b.i << endl; d.~C();
d.~C();
cout << "finish." << endl;
return ;
}
运行结果如下:
test_con
class A
,next:0x77be2850,i:
,next:,i:
,next:,i:
~C()
~C()
finish.
~C()
~B()
~B()
~B()
实际中继承中虚表的构造通过在构造函数中完成,编译器自动将构造过程添加至构造函数前面如类C中,添加的构造函数通过内联展开才能满足非局部对象初始化不为0:
C():px(new A()) {
//构造虚表过程在此完成
px->out(); //此时已经实现虚表构造,调用多态化
}