Overloading a virtual function in a child class

前端 未结 6 1656
一向
一向 2021-01-08 01:04

I am just testing with virtual keyword and inheritance concepts in c++. I have written a small program:

#include
#include

us         


        
6条回答
  •  臣服心动
    2021-01-08 01:35

    Ideally your print that takes an int should have a different name but given you want both functions to be called print, you should make them both non-virtual and make them call protected virtual functions.

    class cna_MO 
    {   
        public:     
         void print() { doPrint(); }
    
        protected:
         virtual void doPrint()
          {         cout << "cna_MO" << endl;     
          } 
    };  
    
    
    class cna_bsc:public cna_MO 
    {   
        protected:     
           virtual void doPrint()  
                      // although with implementation no need to override it
           {         
                cna_MO::print();     
           } 
    
        public:
         void print(int a)    
          {
              doPrintInt( a );
          }
    
        protected:
          virtual void doPrintInt( int )
          {
            cout << "cna_BSC" << endl;     
          } 
     };  
    

提交回复
热议问题