zoukankan      html  css  js  c++  java
  • 《Cracking the Coding Interview》——第13章:C和C++——题目3

    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.
    ", &d);
    50     printf("The address of e is %p.
    ", &e);
    51     printf("The address of d.f is %p.
    ", (&D::f));
    52     printf("The address of e.f is %p.
    ", (&E::f));
    53 
    54     memcpy(&ui, &d, 4);
    55     printf("d = %X
    ", ui);
    56     memcpy(&ui, &e, 4);
    57     printf("e = %X
    ", ui);
    58     memcpy(&ui, ptr, 4);
    59     printf("*ptr = %X
    ", ui);
    60 
    61     return 0;
    62 }
  • 相关阅读:
    2020 商业计划书
    LBDP数据采集网关的设计要求
    Net学习日记_ASP.Net_Ajax
    Net学习日记_ASP.Net_WebForm_笔记
    Net学习日记_ASP.Net_WebForm
    Net学习日记_ASP.Net_一般处理程序_笔记
    Net学习日记_ASP.Net_一般处理程序
    Net学习日记_聊天室(基于Socket,Thread)_服务器软件
    Net学习日记_聊天室(基于Socket,Thread)
    Net学习日记_泛型与反射_笔记
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3689884.html
Copyright © 2011-2022 走看看