c++多重继承

来源:互联网 发布:七天网络查分登陆入口w 编辑:程序博客网 时间:2024/06/06 02:00

c++多重继承


二义性问题:
  一般说来,在派生类中对基类成员的访问应该是唯一的,但是,由于多继承情况下,可能造成对基类中某成员的访问出现了不唯一的情况,则称为对基类成员访问的二义性问题。

       通常再实际的是使用情况中,多重继承主要是用来进行接口的使用的。相当于java中的interface关键字。

实际例子:

#include <iostream>using namespace std;/**说明:接口1*/class Interface_1 {public:    virtual        int add () = 0{};    virtual         int subtract () = 0{};};/**说明:接口2*/class Interface_2 {public:    virtual        void printf () = 0{};};/**说明:父类*/class Base {public:    int m_iA;    int m_iB;public:    Base ()    :    m_iA (10),    m_iB (5){}};/**说明:子类进行多重继承实现接口*/class Child :public Base, public Interface_1, public Interface_2{public:    int add () {            return m_iA + m_iB;    }    int subtract () {            return m_iA - m_iB;    }    void printf () {            cout << "子类!" << endl;    }};int main () {    Child c;    cout << c.add () << endl;    cout << c.subtract () << endl;    c.printf ();    system ("pause");}

优化版

#include <iostream>using namespace std;/**说明:接口1*/class Interface_1 {public:    virtual        int add () = 0{};    virtual         int subtract () = 0{};};/**说明:接口2*/class Interface_2 {public:    virtual        void printf () = 0{};};/**说明:父类*/class Base {public:    int m_iA;    int m_iB;public:    Base ()    :    m_iA (10),    m_iB (5){}};/**说明:子类进行多重继承实现接口*/class Child :public Base, public Interface_1, public Interface_2{public:    int add () {            return m_iA + m_iB;    }    int subtract () {            return m_iA - m_iB;    }    void printf () {            cout << "子类!" << endl;    }};int main () {    Child c;    Interface_1 *pBase_1 = &c;    Interface_2 *pBase_2 = &c;    cout << pBase_1->add () << endl;    cout << pBase_1->subtract () << endl;    pBase_2->printf ();    system ("pause");}









1 0
原创粉丝点击