2014-04-25 19:42
题目:C++中虚函数的工作原理?
解法:虚函数表?细节呢?要是懂汇编我就能钻的再深点了。我试着写了点测大小、打印指针地址之类的代码,能起点管中窥豹的作用,从编译器的外部感受下虚函数表、虚函数指针的存在。
代码:
1 // 13.3 How does virtual function works in C++? 2 #include <cstring> 3 #include <iostream> 4 using namespace std; 5 6 class A { 7 }; 8 9 class B { 10 public: 11 void f() {cout << "class B" << endl;}; 12 }; 13 14 class C { 15 public: 16 C(); 17 }; 18 19 class D { 20 public: 21 virtual void f() { 22 cout << "class D" << endl; 23 }; 24 }; 25 26 class E: public D { 27 public: 28 void f() { 29 cout << "class E" << endl; 30 }; 31 }; 32 33 int main() 34 { 35 D *ptr = new E(); 36 D d; 37 E e; 38 unsigned ui; 39 40 cout << sizeof(A) << endl; 41 cout << sizeof(B) << endl; 42 cout << sizeof(C) << endl; 43 cout << sizeof(D) << endl; 44 cout << sizeof(E) << endl; 45 // The result is 1 1 1 4 4 on Visual Studio 2012. 46 ptr->f(); 47 // class with no data member have to occupy 1 byte, so as to have an address. 48 // class with virtual functions need a pointer to the virtual function table. 49 printf("The address of d is %p.\n", &d); 50 printf("The address of e is %p.\n", &e); 51 printf("The address of d.f is %p.\n", (&D::f)); 52 printf("The address of e.f is %p.\n", (&E::f)); 53 54 memcpy(&ui, &d, 4); 55 printf("d = %X\n", ui); 56 memcpy(&ui, &e, 4); 57 printf("e = %X\n", ui); 58 memcpy(&ui, ptr, 4); 59 printf("*ptr = %X\n", ui); 60 61 return 0; 62 }