在C ++中覆盖虚函数时,是否可以更改返回类型? [英] it is possible to change return type when override a virtual function in C++?
问题描述
我遇到了关于覆盖虚拟函数的问题,事实上,它是关于hessian(一个Web服务协议)。
I encounter a problems about override virtual functions, in fact,it is about hessian (a web service protocol).
它有一个基类Object,派生类:Long,Int,String,...,所有派生类都有一个无虚函数value。
it has a base class Object, and some derived classes : Long,Int,String,...,all derived classes has a no-virtual function "value"
class Object
{
...
};
class Long :public Object
{
...
public:
typedef long long basic_type;
basic_type value(){return value_;}
private:
basic_type value_;
...
};
class Int :public Object
{
...
public:
typedef int basic_type;
basic_type value(){return value_;}
private:
basic_type value_;
...
};
现在我想添加一个函数,例如toString,它可以将Object转换为字符串: / p>
now I want to add a function ,say, toString ,which can convert Object to a string:
Object *obj = ...
cout<<obj->toString();
如果我可以将值函数更改为virtual,我只需要在Object中写一个toString函数,否则,我需要写一个虚函数toString,并在所有派生类中覆盖此函数。
if I can change the value function to virtual ,I only need to write a toString function in Object, else, I need to write a virtual function toString, and to override this functions in all derived classes.
例如
class Object
{
virtual Type value(); // It seemed that I can't write a function like this,because the Type is different for different derived classes
std::string toString()
{
some_convert_function(value());
}
};
但我不能写虚拟值函数,因为返回值不能覆盖。
but I can't write a virtual value function because of return value can't be override.
这个问题有没有什么好的解决方案?
is there any good solution for this issue?
感谢
推荐答案
对象使用虚拟值函数并覆盖返回类型。但是你可以写一个虚拟的toString和模板编程技巧完成几乎相同的事情。
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 long> Long;
typedef BasicType<int> Int;
这篇关于在C ++中覆盖虚函数时,是否可以更改返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!