zoukankan      html  css  js  c++  java
  • C++语法小记---多重继承

    多重继承
    • 工程中不建议使用多继承,因为多继承带来的问题比带来的便利多,已被放弃

    • 问题一:多重继承的对象,向上获取指针时,有不同的地址 ----无法解决

    • 问题二:菱形继承问题,导致成员冗余 ----虚继承(各种编译器的实现方式不一致,不具备抑制性)

    • 多重继承产生多个虚函数表,建议使用dynmaic_cast进行类型转换

    • 工程中的用法:单继承 + 多接口

     1 #include <iostream>
     2 #include <string>
     3 
     4 using namespace std;
     5 
     6 class Base
     7 {
     8     int mi;
     9 public:
    10     Base(int i) : mi(i)
    11     {
    12     }
    13     
    14     int getI()
    15     {
    16         return mi;
    17     }
    18     
    19     bool Equal(Base *p)
    20     {
    21         return (p == this);
    22     }
    23 };
    24 
    25 class Interface1
    26 {
    27 public:
    28     virtual void show1() = 0;
    29 };
    30 
    31 class Interface2
    32 {
    33 public:
    34     virtual void show2() = 0;
    35 };
    36 
    37 class Derived : public Base, public Interface1, public Interface2
    38 {
    39     int mj;
    40 public:
    41     Derived(int i, int j) : Base(i), mj(j)
    42     {
    43     }
    44     
    45     int getJ()
    46     {
    47         return mj;
    48     }
    49     
    50     void show1()
    51     {
    52         cout<<"show1()"<<endl;
    53     }
    54     
    55     void show2()
    56     {
    57         cout<<"show2()"<<endl;
    58     }
    59     
    60 };
    61 
    62 int main()
    63 {   
    64     Derived d(1, 2);
    65     cout<<"d.getI() = "<< d.getI() <<endl;
    66     cout<<"d.getJ() = "<< d.getJ() <<endl;
    67 
    68     Interface1 *p1 = &d;
    69     Interface2 *p2 = &d;
    70     cout<<"p1 = "<<p1<<endl; 
    71     cout<<"p2 = "<<p2<<endl;  //同一个对象获得不同地址
    72     
    73     //基类中定义equal函数,利用dynamic_cast转型,判断是否是同一个对象
    74     if( d.Equal(dynamic_cast<Base*>(p1)) ) 
    75     {
    76         cout<<"p1 == &d"<<endl;  //输出p1 == &d
    77     }
    78     
    79     if( d.Equal(dynamic_cast<Base*>(p2)) )
    80     {
    81         cout<<"p2 == &d"<<endl; //输出p2 == &d
    82     }
    83     
    84     return 0;
    85 }
  • 相关阅读:
    MidPayinfoVO
    IPayablebillItf
    预算oracle
    oracle怎么查看表字段的类型
    orcale授权
    ORCAL
    【转】Oracle
    其他网站api
    生成pdf入门
    有关一个java项目到eclipse中运行
  • 原文地址:https://www.cnblogs.com/chusiyong/p/11313026.html
Copyright © 2011-2022 走看看