Multiple Inheritance

前端 未结 4 910
离开以前
离开以前 2021-01-17 04:42
#include
using namespace std;

class A

{
   int a;
   int b;
   public:
   void eat()
   {
      cout<<\"A::eat()\"<

        
4条回答
  •  别那么骄傲
    2021-01-17 05:23

    Inheriting twice

    With double inheritance you have an ambiguity - the compiler cannot know which of the two A bases do you want to use. If you want to have two A bases (sometimes you may want to do this), you may select between them by casting to B or C. The most appropriate from default casts here is the static_cast (as the weakest available), however it is not realy needed (it is still stronger than your case needs), as you are not casting to a derived type. A custom safe_cast template should do the job:

    /// cast using implicit conversions only
    template 
    inline To safe_cast( const From &from ) {return from;}
    
    main()
    {
    
      D obj;
      foo(safe_cast(&obj)); //error. How do i call with D's B part.
    
    }
    

    Compile time types - use templates

    Also, in case of virtual inheritance, why the offset information need to be stored in the vtable. This can be determined at the compile time itself. In the above case, if we pass foo with D's object, at compile time only we can calculate the offset of D's A part.

    This is a misconception. The foo function as it is written now has no compile type information about ptr type other than it is A *, even if you pass B * or C*. If you want foo to be able to act based on the type passed compile time, you need to use templates:

    template 
    int foo(TypeDerivedFromA *ptr)
    {
      ptr->eat();
    }
    

    Virtual Inheritance

    Your questions mentions virtual inheritance. If you want to use virtual inheritance, you need to specify so:

    class B: public virtual A ...
    
    class C: public virtual A ...
    

    With this the code would compile, but with this solution there is no way you could select between B::A or C::A (there is only one A), therefore this is probably not what you are about.

    Virtual functions

    Furthermore, your questions seems to be confusing two different concepts, virtual inheritance (which means sharing one base class between two intermediate base classes) and virtual functions (which mean allowing derived class function to be called via base class pointer). If you want the B::eat to be called using A pointer, you can do this without virtual inheritance (actually virtual inheritance would prevent you doing so, as explained above), using virtual functions:

    class A
    {
       int a;
       int b;
    
       public:
       virtual void eat()
       {
          cout<<"A::eat()"<

    If virtual functions are not acceptable for you, the compile time mechanism for this are templates, as explained above.

提交回复
热议问题