C++中的RAII机制指明”对象创建时通过构造函数进行初始化,析构时通过析构函数释放资源”,但实际中因类无构造函数时编译器将自动合成一个默认构造函数,该构造函数只服务于自身编译器构造需要而不负责对象成员构造,如这个实例中对象A成员val,next均未进行初始化,而对象B由于是类对象则调用其默认构造函数。但全局对象,静态对象编译器则自动进行将其初始化为0.
1 #include <iostream> 2 3 using namespace std; 4 5 class X { 6 public: 7 virtual void out() { 8 cout << "class X" << endl; 9 } 10 }; 11 12 class B :public X{ 13 public: 14 int i; 15 ~B() 16 { 17 cout << "~B()" << endl; 18 } 19 20 virtual void out() { 21 cout << "class B" << endl; 22 } 23 }; 24 25 class A :public X{ 26 public: 27 int val; 28 A *next; 29 B b; 30 virtual void out() { 31 cout << "class A" << endl; 32 } 33 }; 34 35 class C:public X { 36 X *px; 37 public: 38 C():px(new A()) { 39 px->out(); 40 } 41 ~C() { 42 delete px; 43 cout << "~C()" << endl; 44 } 45 }; 46 47 A b; 48 static A c; 49 int main(int argc, char *argv[]) { 50 51 A a; 52 53 C d; 54 //d.C::C(); 55 cout << a.val << ",next:" << a.next << ",i:" << a.b.i<< endl; 56 cout << b.val << ",next:" << b.next << ",i:" << b.b.i << endl; 57 cout << c.val << ",next:" << c.next << ",i:" << c.b.i << endl; 58 59 d.~C(); 60 d.~C(); 61 cout << "finish." << endl; 62 return 0; 63 }
运行结果如下:
1 test_con 2 class A 3 2009095316,next:0x77be2850,i:2009091625 4 0,next:0,i:0 5 0,next:0,i:0 6 ~C() 7 ~C() 8 finish. 9 ~C() 10 ~B() 11 ~B() 12 ~B()
实际中继承中虚表的构造通过在构造函数中完成,编译器自动将构造过程添加至构造函数前面如类C中,添加的构造函数通过内联展开才能满足非局部对象初始化不为0:
1 C():px(new A()) { 2 //构造虚表过程在此完成 3 px->out(); //此时已经实现虚表构造,调用多态化 4 }
时间: 2024-10-12 04:46:09