【发布时间】:2018-08-01 16:12:56
【问题描述】:
int main()
{
string str;
cout << "Enter Infix Expression \n";
cin >> str;
cout << "infix:" << str << "\n";
string postfix = InfixToPostfix(str); // **error cause here**
cout << "postfix: " << postfix << "\n\n";
system("pause");
return 0;
}
// Function to evaluate Postfix expression and return output
template <class T>
string InfixToPostfix(string& str)
{
Stack<char> *charStackPtr;
charStackPtr = new Stack<char>();
string postfix = ""; // Initialize postfix as empty string.
for (int i = 0; i< str.length(); i++) {
// If character is operator, pop two elements from stack, perform operation and push the result back.
if (IsOperator(str[i]))
{
while (!charStackPtr.empty() && charStackPtr.top() != '(' && HasHigherPrecedence(charStackPtr.top(), str[i]))
{
postfix += charStackPtr.top();
charStackPtr.pop();
}
charStackPtr.push(str[i]);
}
// Else if character is an operand
else if (IsOperand(str[i]))
{
postfix += str[i];
}
else if (str[i] == '(')
{
charStackPtr.push(str[i]);
}
else if (str[i] == ')')
{
while (!charStackPtr.empty() && charStackPtr.top() != '(') {
postfix += charStackPtr.top();
charStackPtr.pop();
}
charStackPtr.pop();
}
}while (!charStackPtr.empty()) {
postfix += charStackPtr.top();
charStackPtr.pop();
}
delete charStackPtr;
return postfix;
}
谁能帮我为什么我不能运行程序,我总是犯3个错误:
错误 C2672 'InfixToPostfix':没有匹配的重载函数 找到了
错误 C2783 'std::string InfixToPostfix(std::string)': 不能 推导出 'T' 的模板参数
E0304 没有重载函数“InfixToPostfix”的实例匹配 参数列表
【问题讨论】:
-
如果你不使用那个类型,为什么它是一个模板?
-
如果你根本不使用
T,为什么还要有template <class T>? -
我正在尝试使用我创建的堆栈模板,而不是来自库
-
删除
template <class T>并重新编译。 -
所以你在没有
T的情况下使用它,那么为什么你需要你的函数作为模板呢?这与你的堆栈有什么关系?如果您想在 main 中尝试您的 Stack(用于测试),您是否也会尝试制作 main模板?
标签: c++ class templates error-handling