【问题标题】:Error: No matching function found错误:找不到匹配的函数
【发布时间】:2014-08-04 19:20:38
【问题描述】:

我收到一条错误消息:

error: no matching function for call to 'Expression::shuntingYard(Expression&)'

当函数在名为 Expression.h 的头文件夹中声明时。我看不出有什么问题。我还包括了所有必要的预处理器指令。

包括以下文件:

main.cpp

#include <iostream>
#include "Expression.h"

using namespace std;

int main()
{
    Expression expr("2 * (3 + 1)");

    //Set x = 5
    //expr.instantiateVariable('x',5);
    //Set y = 3
    //expr.instantiateVariable('y',3);

    cout << "Answer: " << expr.shuntingYard(expr) << endl;
}

表达式.h

#ifndef EXPRESSION_H
#define EXPRESSION_H

#include <string>
#include <iostream>

using namespace std;

class Expression
{
    private:
        string expression;
    public:
        Expression(string expr);
        ~Expression();
        void instantiateVariable(char name, int value);

        //Function to calculate the postFix string made by the ShuntingYard function
        int evaluate(string, int, int);

        //Function to convert infix expression to postfix
        string shuntingYard(string);

        //Other
        int higherPrecedence(char operator1, char operator2);
        bool IsOperator(char C);
        bool IsOperand(char C);
};

#endif

如果您能指出我做错了什么,收到此错误,我将不胜感激。

谢谢。

【问题讨论】:

  • 所以你没有这样的函数签名,你也没有提供从Expressionstd::string的任何自动转换。

标签: c++ function class object compiler-errors


【解决方案1】:

声明的函数 shuntingYard 通过值获取 string,而不是通过引用获取 Expression

附带说明,将operator string() 添加到class Expression 可以解决您的问题:

operator string() const
{
    return expression;
}

补充

这也是一种选择(我个人更喜欢):

operator string&() const
{
    return expression;
}

在这种情况下,删除const 将允许您在外部更改expression 成员变量。

【讨论】:

    【解决方案2】:

    在你声明函数的类定义中

    string shuntingYard(string);
    

    具有std::string 类型的参数

    但是在 main 中,您调用具有相同名称但传递类型为 Expression 的参数的函数

    cout << "Answer: " << expr.shuntingYard(expr) << endl;
    

    并且类定义中没有Expression类型对象到std::string类型对象的转换函数可以隐式调用。

    所以编译器看不到被调用函数的声明并发出错误。

    这是错误的类设计的结果。函数shuntingYard 必须使用数据成员string expression; 而不是用作参数的字符串。也就是函数声明应该不带参数。

    【讨论】:

      猜你喜欢
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 2018-04-09
      相关资源
      最近更新 更多