[英]Is it possible to call a subclass virtual function from within superclass implementation?
[英]Call virtual function from another subclass
我已被分配一个任务,以创建一个以中缀表示法作为输入的rpn计算器。 因此,部分原因是必须打印出流程的不同阶段。 因此,首先应将字符串分成标记,然后再存储在向量中。 然后将其转换为rpn表示法(例如3 + 4-> 3 4 +),这是我现在固定的部分。
建议我为此使用虚拟抽象函数。 所以首先我创建一个带有抽象函数的类。 然后,我创建一个子类,该子类将字符串转换为存储在字符串向量中的令牌,这部分工作正常。 然后,我应该创建另一个将输入字符串转换为rpn表示法的子类,因此我必须在该子类的开头调用函数以将其转换为令牌,这是我认为出错的地方。
我已经得到了一些作为模板的代码,到目前为止,它是非常有问题的,因此错误所在的语法可能存在问题。
所以我把这作为我的主要课程
template<typename T> class tokenstream { public: virtual bool process(const std::string& input, std::vector<T>& output) = 0; };
然后将此作为第一个子类
class tokenifier: public tokenstream<std::string> {
public:
bool process(const std::string& input, std::vector<std::string>& output) {
//this part works fine, ive tested it.
};
因此,我必须创建另一个子类,然后在其中调用上面的函数,这是出错的部分。
class infix2rpn: public tokenstream<std::string> {
private:
tokenifier *tokens;
public:
tokenifier(tokenstream *_tokens): tokens(_tokens) {} //I think this line is the problem
bool process(const std::string& input, std::vector<std::string>& output) {
//call the underlying tokenstream object
std::vector<std::string> infixtokens;
if(!tokens->process(input, infixtokens))
{
return false;
}
return shunting_yard(infixtokens, output);
}
bool shunting_yard(const std::vector<std::string>& input, std::vector<std::string>& output){
//i've tested the shunting_yard algorithm and it works fine
}
};
当我尝试对其进行编译时,出现错误“ ISO C ++禁止无类型[-fpermissive]的'tokenifier'声明。
因此,我不了解的部分是如何从另一个子类调用其他虚函数。
谢谢
tokenifier(tokenstream *_tokens): tokens(_tokens) {}
这可能是构造函数,但在这种情况下,方法的名称应为infix2rpn
,与类名相同。 该错误意味着,您指定的方法tokenifier
未指定返回类型,只有构造函数和析构函数没有返回类型。
请注意, void
还指定了返回类型,在这种情况下,它意味着什么也没有返回。
您的类称为infix2rpn
,因此其构造函数也应命名为infix2rpn
,而不是tokenifier
。 这与虚函数无关。
此外,您的属性应该是tokenstream<std::string>*
,而不是tokenifier*
,因为您无法将构造函数中获得的tokenstream<std::string>*
转换为tokenifier*
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.