it is possible to change return type when override a virtual function in C++?

后端 未结 6 1407
醉梦人生
醉梦人生 2020-12-16 03:34

I encounter a problems about override virtual functions, in fact,it is about hessian (a web service protocol).

it has a base class Object, and some derived classes :

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 04:12

    No, you can't write toString in Object using a virtual 'value' function and override the return type. However you can write a virtual toString and with a template programming trick accomplish almost the same thing.

    class Object
    {
    public:
      virtual std::string toString();
    }
    
    
    template < class ValueType >
    class BasicType : Object
    {
      public:
      typedef ValueType basic_type;
      basic_type value() { return value_; }
    
      std::string toString()
      {
        return some_convert_function( value_ );
      }
    
      private:
      basic_type value_;
    }
    
    typedef BasicType Long;
    typedef BasicType       Int;
    

提交回复
热议问题