zoukankan      html  css  js  c++  java
  • C++ 虚函数

     1 using namespace std;
     2 #include <iostream>
     3 
     4 using namespace std;
     5 
     6 class A{                                                                                                                                                                                        
     7 public:
     8     virtual void Fun1(){
     9         cout << "A::Func1" << endl;
    10     }   
    11 
    12     virtual void Fun2(){
    13         cout << "A::Func2" << endl;
    14     }   
    15 };
    16 
    17 class B : public A{
    18 public:
    19     virtual void Fun1(){
    20         cout << "B::Func1" << endl;
    21     }   
    22 
    23     virtual void Fun3(){
    24         cout << "B::Func3" << endl;
    25     }   
    26 };
    27 
    28 class C : public B{
    29 public:
    30     virtual void Fun1(){
    31         cout << "C::Func1" << endl;
    32     }   
    33 
    34     virtual void Fun4(){
    35         cout << "C::Func4" << endl;
    36     }   
    37 };
    38 
    39 typedef void(*FUNC)();
    40 int main()
    41 {
    42     A a;
    43     cout << "A::虚表" << endl << endl;
    44     ((FUNC)(*(long*)(*(long*)(&a))))();
    45     ((FUNC)(*((long*)(*(long*)(&a)) + 1)))();
    46     cout << "------------------------" << endl;
    47 
    48     B b;
    49     cout << "B::虚表" << endl << endl;
    50     ((FUNC)(*(long*)(*(long*)(&b))))();
    51     ((FUNC)(*((long*)(*(long*)(&b)) + 1)))();
    52     ((FUNC)(*((long*)(*(long*)(&b)) + 2)))();
    53     cout << "------------------------" << endl;
    54 
    55     C c;
    56     cout << "C::虚表" << endl << endl;
    57     ((FUNC)(*(long*)(*(long*)(&c))))();
    58     ((FUNC)(*((long*)(*(long*)(&c)) + 1)))();
    59     ((FUNC)(*((long*)(*(long*)(&c)) + 2)))();
    60     ((FUNC)(*((long*)(*(long*)(&c)) + 3)))();
    61     cout << "------------------------" << endl;
    62     return 0;
    63 }  
    虚函数

      虚函数表继承替换原则:

    有则替换, 无则末尾追加。

  • 相关阅读:
    css3正方体效果
    单行文本溢出和多行文本溢出变省略号
    iscroll的滑动效果
    angular笔记
    html页面的css样式、meta最常用的最基本最常规的配置参数
    解决webstorm卡顿问题
    pc端网页的设计尺寸
    时间字符串解析成日期时间格式
    Inf2Cat, signability test failed.
    #pragma once 与 #ifndef 解析(转载)
  • 原文地址:https://www.cnblogs.com/sanghai/p/6524978.html
Copyright © 2011-2022 走看看