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 }
  • 相关阅读:
    Thinkphp的 is null 查询条件是什么,以及exp表达式如何使用
    thinkphp5多文件上传如何实现
    如何动态改变audio的播放的src
    js插件---10个免费开源的JS音乐播放器插件
    html5页面怎么播放音频和视频
    Thinkphp5图片上传正常,音频和视频上传失败的原因及解决
    leetcode
    HTML5 画一张图
    Linux内核和根文件系统引导加载程序
    [dp] hdu 4472 Count
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3689884.html
Copyright © 2011-2022 走看看