C++ 多重继承详细教程(三)

2014-02-14 12:51:47 · 作者: · 浏览: 360


    ***多重继承歧义函数解决定式(multiple inheritance function ambiguity idiom)。
    例:***
    #include<iostream>
    using namespace std;
    class R
    {
    int r;
    public:
    R(int x=0):r(x) {}
    void f(){cout 《 "r=" 《 endl;}
    };
    class A:virtual public R
    {
    int a;
    protected:
    void fA(){cout 《 "a=" 《 a 《 endl;};
    public:
    A(int x, int y):R(x), a(y){}
    void f() {fA();R::f();}  //看不出区别;
    };
    class B:virtual public R
    {
    int b;
    protected:
    void fB(){cout 《 "b=" 《 b 《 endl;};
    public:

    B(int x, int y):R(x),b(y){}
    void f() {fB();R::f();}  //看不出区别;
    };
    class C:public A, public B
    {
    int c;
    protected:
    void fC() {cout 《 "c=" 《 c 《 endl;};
    public:
    C(int x, int y, int z, int w):R(x),A(x,y),B(x,z),c(w) {}
    void f()   //拆分后只调用了一次f();
    {
    R::f();
    A::fA();
    B::fB();
    fC();
    }
    };
    void main()
    {
    R rr(1000);
    A aa(2222,444);
    B bb(3333,111);
    C cc(1212,345,123,45);
    cc.f();
    }