[英]Problems while making a stack in C++ with auto referenced classes
我正在 C++ 中创建一个堆栈来管理中缀、后缀和前缀数学运算。 我使用 2 个类,一个称为 Node(一个自动引用的类),另一个称为 Stack。 在节点中,我有 2 个属性,一个是 ID(一个 int,仅用于测试)和 element(是一个 char*)。 在堆栈中,我管理 2 个堆栈中的所有节点,一个堆栈管理操作数 (stack1),另一个堆栈管理运算符 (stack2)。 如果我使用表达式:“53+72-30/38*912”,则想法是,例如在 stack2 中,我应该有 [ *, /, -, +] 和每个 object [4, 3, 2, 1],但是 stack2 的结果如下 [ *, *, *, *] 但每个的 id 都很好 [4, 3, 2, 1]
我认为问题必须与char *有关,但我不知道如何解决它,你能帮我吗?
提前致谢!
Stack.cpp
//this is inside of a loop that goes trough a char* (named expr) char tmp[i] = expr[i]; char op[] = {tmp, '\0'}; //I do this because the constructor of Node requieres a char*, //and it is because I use the class Node to manage the stack of operands, which are char* //for example, '983' (I do not use int for this case, but I also may create a template... //but I want to know how to make it with char*) this->addOperatorToStack2(op);
Stack.cpp
//The method that adds an operator (a new node) to the stack
void Stack::addOperatorToStack2(char *op){
Node *tmpNode = new Node(op);
if(!currentNode){
currentNode = tmpNode;
}
else{
tmpNode->nextNode = currentNode;
currentNode= tmpNode;
}
}
Node.h
#ifndef NODE_H
#define NODE_H
class Node{
friend class Stack;
public:
Node(char *);
char* getElement() const;
private:
char *element;
Node *nextNode;
static int counter;
int id;
};
#endif
Node.cpp
#include "Node.h"
Node::Node(char *element){
this->nextNode = 0;
this->element = element;
counter++;
id = counter;
}
char* Node::getElement()const{
return this->element;
}
int Node::counter= 0;
每个节点应拥有其元素值:
class Node{
private:
char element[MAXSIZE];
};
因此,您的构造函数Node::Node(const char *element)
应制作自己的值副本 - strncpy
或类似的一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.