polymorphic C++ references

前端 未结 7 1073
闹比i
闹比i 2020-12-09 09:07

I was wondering how you can do polymorphism with references, as opposed to pointers.

To clarify, see the following minimal example:

cl         


        
7条回答
  •  无人及你
    2020-12-09 10:03

    Erm, is this not sufficient?

    #include 
    
    struct A;
    
    struct B
    {
      B(A& a);
    
      void foo();
    
      A& _a;
    };
    
    struct A
    {
      virtual void foo() =0;
    };
    
    struct A1 : public A
    {
      virtual void foo() { std::cout << "A1::foo" << std::endl; }
    };
    
    B::B(A& a) : _a(a) {}
    void B::foo() { _a.foo(); }
    
    
    int main(void)
    { 
      A1 a;  // instance of A1
      B b(a); // construct B with it
    
      b.foo();
    }
    

提交回复
热议问题