C++ 使用不同的返回类型重写基类函数

C++ 使用不同的返回类型重写基类函数,c++,templates,inheritance,C++,Templates,Inheritance,我有一个名为Variable的基类: class Variable { protected: std::string name; public: Variable(std::string name=""); Variable (const Variable& other); virtual ~Variable(){}; }; 我有几个派生类,如Int、Bool、String等。例如: class Bool: public Variable{ pri

我有一个名为Variable的基类:

class Variable
{
protected:
    std::string name;   
public:
    Variable(std::string name="");
    Variable (const Variable& other);
    virtual ~Variable(){};
};
我有几个派生类,如Int、Bool、String等。例如:

class Bool: public Variable{
private:
    bool value;

public:
    Bool(std::string name, bool num);
    ~Bool();
    Bool (const Bool& other);
    bool getVal();
每个派生类都有一个名为getVal()的方法,该方法返回不同的类型(bool、int等)。我想允许变量类的多态行为。
我试过:
void getVal()
这似乎是错误的,编译器显示了一个错误:
shadows Variable::getVal()
这听起来很糟糕。 我想使用
template T getVal()但它没有帮助

有什么建议吗?我必须使用铸造吗

非常感谢……

您。我认为模板在你的情况下会更好。这里不需要多态性或继承:

template<class T>
class Variable {
protected:
    T value;
    std::string name;   
public:
    Variable(std::string n, T v);
    Variable (const Variable& other);
    virtual ~Variable(){};
    T getVal();
};
模板
类变量{
受保护的:
T值;
std::字符串名;
公众:
变量(std::字符串n,tv);
变量(常量变量和其他);
virtual~Variable(){};
T getVal();
};
其用途是:

可变条件(“Name”,true);
变量字符(“Name2”,“T”);
变量整数(“名称3”,123);

std::cout类型是在编译时确定的。因此,任何多态性都不允许您更改返回类型。
虚拟分派在运行时完成,但方法和对象的类型必须正确,并且在编译时必须相同


如果只需要打印值,只需添加virtual-ToString()方法。如果您不想为每个派生类型再次编写,甚至可以将i模板化。

显示您在基类和派生类中尝试的内容
Variable condition=condition\u语句。evaluate(type)
//Where
condition\u语句。evaluate(type)
返回Bool对象
请注意,在重写函数时只能有协变返回类型,否则将隐藏基类函数,这不是您想要的行为。
cout
如何知道要打印的类型?这只是一个示例
condition.getVal()
应返回bool。但它也可以是字符串、int或folat。这取决于对象的类型。Bool的getVal()返回Bool,Int的getVal()返回Int等。我希望能够在类变量中创建一个方法getVal(),该方法将被派生类的getVal()覆盖。谢谢。但是我需要不同的派生类(例如Bool、String、Int、Float和其他)具有不同的运算符重载行为。假设我需要Int来覆盖运算符+并最终添加值,但是如果尝试Bool+Bool,Bool应该抛出异常。我如何使用模板来做到这一点?@Shakedk,这不是问题。就用吧。看起来有点复杂,但我会试试的。非常感谢。
Variable<bool> condition("Name", true);
Variable<char> character("Name2", 'T');
Variable<unsigned> integer("Name3", 123);
std::cout << condition.getVal() << '\n';
std::cout << character.getVal() << '\n';
std::cout << integer.getVal() << '\n';