创建从C++的对象的队列

发布于 2025-02-06 22:41:08 字数 1212 浏览 1 评论 0原文

因此,简而言之,我正在编写一个相当简单的计算器(用于反向抛光符号)。我的基类是符号,它是一个纯虚拟类,我还有其他类:

操作数:从符号继承
数字:从操作数继承
常数:从操作数继承
继承

变量:从操作数函数

:从符号继承,现在我想将字符串解析为对象的队列/向量,同时仍然能够使用其单个方法。我的尝试失败了,并遇到了切片,我认为这是在我的情况下发生的。

std::queue<Symbol*> parse(std::string s){
//split is custom function for converting string -> (ListOf string) without whitespaces
std::queue<std::string> StringExps = split(s);
std::queue<Symbol*> Q;

while(!StringExps.empty()){
    std::string expr = StringExps.front();
    StringExps.pop();
    // now i want to be able to use get_val, from Number class, this throws an exception
    if( '0' <= expr[0] && expr[0] <= '9'){
        Q.push(new Number(std::stoi(expr)));
        std::clog<<Q.front()->get_val()<<"\n";
    }
    //checking if expr is a valid function ("min" "+" "sin" etc.)
    else if(checkif_function(expr)){
        Q.push(new Function(expr));
        std::clog<<Q.front()->return_type()<<"\n";
        //std::clog<<"Funtion/operator\n";
    }
    else if(checkif_const(expr)){
        Q.push(new Const(expr));
    }
}
return Q;}

现在,我需要能够使用每个派生类中的特定方法,但这不起作用,我不知道如何修复它。谁能帮我吗?

So, in short, I am writing a rather simple calculator (for reverse Polish notation). My base class is Symbol, it is a pure virtual class, and I have bunch of other classes:

Operand: inherits from Symbol
Number: inherits from Operand
Constant: inherits from Operand
Variable: inherits from Operand

Function: inherits from Symbol

Now i want to parse a string into queue/vector of objects, while still being able to use their individual methods. I had lots of failed attempts, and came across object slicing which, I think happens in my case.

std::queue<Symbol*> parse(std::string s){
//split is custom function for converting string -> (ListOf string) without whitespaces
std::queue<std::string> StringExps = split(s);
std::queue<Symbol*> Q;

while(!StringExps.empty()){
    std::string expr = StringExps.front();
    StringExps.pop();
    // now i want to be able to use get_val, from Number class, this throws an exception
    if( '0' <= expr[0] && expr[0] <= '9'){
        Q.push(new Number(std::stoi(expr)));
        std::clog<<Q.front()->get_val()<<"\n";
    }
    //checking if expr is a valid function ("min" "+" "sin" etc.)
    else if(checkif_function(expr)){
        Q.push(new Function(expr));
        std::clog<<Q.front()->return_type()<<"\n";
        //std::clog<<"Funtion/operator\n";
    }
    else if(checkif_const(expr)){
        Q.push(new Const(expr));
    }
}
return Q;}

Now I need to be able to use specific methods from each derived class, but this does not work, and I have no idea how to fix it. Could anyone help me with that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文