zoukankan      html  css  js  c++  java
  • 【C++札记】虚继承

    由于多重继承产生的二义性引入了类的虚继承,先看下什么是二义性。

    类D是类B和类C的派生类,而类B,类C就是继承于类A,当D调用类A中的函数时不知道是类B继承A的,还是类C继承A的,引起了二义性。虚继承可以解决这个问题。

    使用语法:

    class 派生类:virtual 继承方式 虚基类
    {
    };

    上图中类D 实例化过程中的初始化顺序:

    祖父类(A)--->父类(从左到又)--->子类,并且最后一次初始化有效

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class A
    {
    public:
        A(int a):i(a)
        {
            cout << "construct A" << endl;
        }
    
        void displaya()
        {
            cout << "A:" << i << endl;
        }
    private:
        int i;
    };
    
    class B:virtual public A   //虚继承
    {
    public:
        B(int a): A(a),i(a)
        {
            cout << "construct B" << endl;
        }
    
        void displayb()
        {
            cout << "B:" << i << endl;
        }
    private:
        int i;
    };
    
    class C:virtual public A   //虚继承
    {
    public:
        C(int a):A(2),i(a)
        {
            cout << "construct C" << endl;
        }
    
        void displayc()
        {
            cout << "C:" << i << endl;
        }
    private:
        int i;
    };
    
    class D: public B, public C //多重继承
    {
    public:
        D(int a, int b, int c, int d):A(a), B(b), C(d), i(c) //必须初始化虚基类X,X(d)
        {
            cout << "construct Z" << endl;
        }
    
        void displayd()
        {
            cout << "D:" << i << endl;
        }
     private:
        int i;
    };
    
    int main()
    {
        D d(1,2,3, 4);
        d.displaya();
        d.displayb();
        d.displayc();
        d.displayd();
    }
    

    运行结果:

    编译器在实例化D时,之调用了一次虚基类的构造函数,忽略了虚基类A派生类B,C对续虚基类构造函数的调用,保证了虚基类的数据成员不会被初始化多次。

  • 相关阅读:
    十六.jQuery源码解析之Sizzle设计思路.htm
    关于微信浏览不能URL传参,URL中的问号被删除
    websocket 通信协议
    java_httpservice
    Socket.Io 做个标记 下来了解下
    通过netty实现服务端与客户端的长连接通讯,及心跳检测。
    NETTY 编码器介绍
    Netty4.0学习教程
    FORM表单不刷新提交POST数据
    Linux0.11学习
  • 原文地址:https://www.cnblogs.com/woniu201/p/11694513.html
Copyright © 2011-2022 走看看