C++ 在不同的函数中使用相同的字符串
我正在研究如何将中缀转换为后缀表达式,然后计算转换后的后缀表达式。关于如何做到这一点,我有以下思考过程C++ 在不同的函数中使用相同的字符串,c++,postfix-notation,infix-notation,C++,Postfix Notation,Infix Notation,我正在研究如何将中缀转换为后缀表达式,然后计算转换后的后缀表达式。关于如何做到这一点,我有以下思考过程 接收中缀表达式(通过主文件) 通过名为InstanceEvariable(char,int)的函数实例化此表达式中的变量 a+(2+2) 式中a=2; 因此,在解析并转换为后缀之前,必须相应地添加这些值 收到中缀表达式并实例化变量后,我想在我的调车场函数中将该中缀“转换”为后缀表达式。我已经设法做到了这一点,而且效果良好 最后,我想计算/评估在我的调车场函数中创建的这个后缀表达式 因此,基本上
void instantiateVariable(char, int)
{
//receive the string through the main.cpp in the expression constructor
//assign the values to the variables;
a * (2 + 2); //set a = 3
//Update, if you may, the "new" infix string
}
string shuntingYard(string)
{
//Receiving this updated infix string
//Convert it
return the postfix string; //The converted string
}
int evaluate(string)
{
//calculate the postfix string in the above shuntingYard function
returns the postfix string's value;
}
这是我正在使用的类:
class Expression
{
private:
//string expression;
public:
/*The constructor receives a string
expression in infix notation*/
Expression(string);
/*The destructor*/
~Expression();
/*Sets a value for a variable in the expression. The
name of the variable (first parameter) and its value
(second parameter) are passed to this function*/
/*Apply values to the variables in the expression*/
void instantiateVariable(char, int);
/*Evaluates and returns the answer to the expression*/
int evaluate(string);
// Function to convert Infix expression to postfix
string shuntingYard(string);
/*Function to verify whether an operator has higher precedence over other*/
int higherPrecedence(char, char);
/*Function to verify whether a character is operator symbol or not*/
bool IsOperator(char);
/*Function to verify whether a character is alphanumeric character (letter or numeric digit) or not*/
bool IsOperand(char);
};
主题是否与问题描述相关?无法将主题与描述联系起来不太确定您要问什么。如果“同一个字符串”只是“避免不必要的拷贝”(例如,当从函数返回字符串值)时,由于移动语义,你应该对现代C++很好。如果你指的是更复杂的东西(保留对同一字符串的多个引用,以便修改其中一个可以修改所有字符串),我同意@Nabin的观点,我不理解你的代码问题。我猜你想使用
void分流场(string&s)代码>。这样,您可以写入已传递的字符串s
,调车场的调用者将看到更改。