【发布时间】:2013-10-06 13:19:26
【问题描述】:
我有一个名为变量的基类:
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 <typename T> T getVal();,但没有帮助。
有什么建议吗?我必须为此使用强制转换吗?
非常感谢...
【问题讨论】:
-
显示您在基类和派生类中尝试的内容
-
Variable condition = condition_statement.evaluate(type);//condition_statement.evaluate(type)返回一个 Bool 对象cout << condition.getval();编译器说:“‘类变量’没有名为‘getVal’的成员” -
请注意,您只能拥有 协变返回类型,而覆盖函数,否则您最终会隐藏基类函数,这不是您想要的行为。
-
cout应该如何知道要打印什么类型? -
这只是一个例子...
condition.getVal()应该返回布尔值。但它也可以是字符串、int 或 folat。这取决于对象的类型。 Bool 的 getVal() 返回 bool,Int 的 getVal() 返回 int 等。我希望能够在类变量中创建方法 getVal(),该方法将被派生类的 getVal() 覆盖。
标签: c++ templates inheritance