从另一个子类调用虚拟函数

Call virtual function from another subclass

本文关键字:虚拟 函数 调用 子类 另一个      更新时间:2023-10-16

我已经设置了一个赋值来创建一个以中缀表示法为输入的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也是返回类型的规范,在这种情况下,它意味着不返回任何内容。