Override a member function with different return type

后端 未结 5 1065
臣服心动
臣服心动 2020-12-01 12:16

Consider the example below:

#include 

using namespace std;

class base
{
   public:
      virtual int func()
      {
         cout <<          


        
5条回答
  •  我在风中等你
    2020-12-01 12:33

    If you want to override, you should try to use template.

    See the following:

    #include 
    
    using namespace std;
    
    class base
    {
       public:
          template X func()
          {
             cout << "vfunc in base class\n";
             return static_cast(0);
          }  
    };    
    
    class derived: public base
    {
       public:
          template X func()
          {
             cout << "vfunc in derived class\n";
             return static_cast(2);
          }  
    };    
    
    int main()
    {
       derived *bptr = new derived;
       cout << bptr->func() << endl;
       cout << dynamic_cast(bptr)->func() << endl;
    
       derived *bptr2 = new derived;
       cout << bptr->func() << endl;
       cout << dynamic_cast(bptr)->func() << endl;
    
    
       return 0;
    }
    

    Of course, you dont need to declare it on two different class that way, you could do:

    class base
    {
       public:
          int func()
          {
             cout << "vfunc in base class\n";
             return 0;
          }  
    
          double func(){
            cout << "vfunc for double class\n";
            return 2.;
    
          }
    };
    

提交回复
热议问题