从另一个子类调用虚函数

时间:2014-04-11 16:55:26

标签: c++ function virtual subclass abstract

我已经设置了一个赋值来创建一个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]。

所以我不理解的部分是如何从另一个子类调用其他虚函数。

由于

2 个答案:

答案 0 :(得分:0)

tokenifier(tokenstream *_tokens): tokens(_tokens) {}

这可能是构造函数,但在这种情况下,方法的名称应为infix2rpn,与类名相同。 该错误意味着您指定了未指定返回类型的方法tokenifier,只有构造函数和析构函数没有返回类型。

请注意,void也指定了返回类型,在这种情况下,它意味着没有返回任何内容。

答案 1 :(得分:0)

您的类名为infix2rpn,因此其构造函数也应该命名为infix2rpn,而不是tokenifier。这与虚函数无关。

此外,您的属性应该是tokenstream<std::string>*,而不是tokenifier*,因为您无法将构建器中获得的tokenstream<std::string>*转换为tokenifier*

相关问题