从另一个子类调用虚拟函数
Call virtual function from another subclass
我已经设置了一个赋值来创建一个以中缀表示法为输入的rpn计算器。因此,部分原因是它必须打印出过程的不同阶段。因此,首先它应该将字符串分离为令牌,然后存储在向量中。然后它应该将其转换为rpn表示法(例如3+4->34+),这是我现在被卡住的部分,也是我现在被粘住的部分。
有人建议我为此使用虚拟抽象函数。所以首先我创建了一个带有抽象函数的类。然后我创建了一个子类,它将字符串转换为存储在字符串向量中的令牌,这部分工作得很好。然后我应该创建另一个子类,它将输入字符串转换为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++禁止声明没有类型[-fpermission]的‘tokenifier’。
所以我不明白的部分是如何从另一个子类调用其他虚拟函数。
感谢
您的类名为infix2rpn
,因此其构造函数也应命名为infix2rpn
,而不是tokenifier
。这与虚拟函数无关。
此外,您的属性应该是tokenstream<std::string>*
,而不是tokenifier*
,因为您无法将构造函数中得到的tokenstream<std::string>*
转换为tokenifier*
。
tokenifier(tokenstream *_tokens): tokens(_tokens) {}
这可能是构造函数,但在这种情况下,方法的名称应该是infix2rpn
,与类名相同。该错误意味着,您指定的方法tokenifier
没有指定返回类型,只有构造函数和析构函数没有返回类型。
请注意,void
也是返回类型的规范,在这种情况下,它意味着不返回任何内容。
- C++无法定义虚拟函数 OUTER 类和头文件
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 类型擦除的std::function与虚拟函数调用的开销
- 重写虚拟函数和继承
- 用纯虚拟函数兜圈子
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 禁止子函数调用父级的抽象(或虚拟)函数
- 无法在子类中使用虚拟函数C++
- 无法在派生对象上运行虚拟函数
- 我可以调用从 main() 覆盖的虚拟函数吗?
- 在 C++ 中将函数获取和设置为虚拟函数
- 使用在堆栈上创建的对象调用虚拟函数
- 为什么在这种情况下不调用我的虚拟函数实现?
- 在C++中使虚拟函数私有化
- 模板继承类中的虚拟函数
- 为什么构造函数的虚拟函数调用有时有效,但其他调用却无效
- doxygenc++虚拟函数和实现
- 如何从派生类函数中调用虚拟函数