Virtual function inheritance

后端 未结 3 2218
忘掉有多难
忘掉有多难 2021-02-20 00:20

I have a confusion about the inheriting the virtual property of a method.

Let\'s suppose we have 4 classes: class A, class B, class C and class D. The classes are inheri

3条回答
  •  猫巷女王i
    2021-02-20 00:34

    You're correct.

    I think that in this case the best solution is to try:

    #include 
    
    using namespace std;
    
    class A {
       public:
          void print(){ cout << "print A" << endl; };
    };
    
    class B: public A {
        public:
           virtual void print(){ cout << "print B" << endl; };
    };
    
    class C: public B {
         public:
            void print(){ cout << "print C" << endl; };
    };
    
    int main()
    {
       A *a = new C();
       B *b = new C();
    
       a->print(); // will print 'print A'
       b->print(); // will print 'print C'
    
       return 1;
    }
    

提交回复
热议问题