编辑:感谢您为我指出循环依赖的正确方向。我尝试从Mathfg.h中删除#include "datastructure.h",并在 "Matfg.h" 中添加了一个 "Class ArithmeticTree" 来转发声明它,但在 CleanExpression 函数中出现另一个错误:
无法转换 'std:: __cxx11::basic_string::iterator {aka __gnu_cxx::__normal_iterator >}' to 'const char*' for argument '1' to 'int remove(const char*)'。当我将鼠标悬停在“删除”一词上时,Qt 告诉我“参数太多”。这是 Calculator::CleanExpression 包含的一行代码。
我正在编写一个数学解析器,并创建了一个头文件Mathfg,其中包含一个处理输入的Calculator类。到目前为止,我有一个名为CleanExpression的静态函数,它只是从输入字符串中删除空格。
我在这里看到了一个有点类似的问题:Static function declared but not defined in C++,但我无法将那里的答案应用于我自己的问题。
(我省略了一些不相关的部分,例如Node结构的实现,但除了CleanExpression调用之外,一切都有效。)
Mathfg.h
#ifndef MATHFG_H
#define MATHFG_H
#include <string>
#include "datastructure.h"
using namespace std;
class Mathfg
{
private:
Mathfg();
};
class Calculator
{
private:
Calculator();
public:
static void CleanExpression(string& expression)
{
expression.erase(remove(expression.begin(), expression.end(), ' '), expression.end());
}
};
#endif // MATHFG_H
注意:我不使用 Mathfg.h 的源文件。
数据结构.h
在另一个标题"Datastructure.h"中,我修复了输入并产生了输出。我想从"Mathfg.h"调用静态函数CleanExpression,但出现错误:'Calculator' has not been declared。
#ifndef DATASTRUCTURE_H
#define DATASTRUCTURE_H
#include <iostream>
#include <string>
#include "mfg\mathfg.h"
using namespace std;
struct ArithmeticTree
{
private:
struct Node
{
// Doing some unrelated stuff here
};
public:
ArithmeticTree()
{
}
ArithmeticTree(string expression_in)
{
Calculator::CleanExpression(expression_in); // <- Here's the problem!
// Doing some unrelated stuff here
}
// Doing some unrelated stuff here
};
#endif // DATASTRUCTURE_H
注意:我不使用 Datastructure.h 的源文件。
有什么作用:
在我的游戏循环中,我可以成功运行以下代码:
std::string str = "2 +3-4 / 5";
cout << "Cleaning string:\t'" << str << "'\n";
Calculator::CleanExpression(str);
cout << "Cleaned:\t\t'" << str << "'\n";
...输出:
Cleaning string: '2 +3-4 / 5'
Cleaned: '2+3-4/5'
...但是当我尝试从“Datastructure.h”中调用Calculator::CleanExpression - 或者更具体地说,从ArithmeticTree的构造函数中调用时 - 我得到了上述错误。我从未在我的代码中的任何地方创建过Calculator或Mathfg对象;我只是调用它的静态函数,就像我通常期望它的行为一样。
我确定我误解了静态函数在 C++ 中的工作方式,这可能也是我的错误的原因。
我真的很想要一些关于如何解决这个问题的提示!
我正在使用Qt Creator 4.2.1和MinGW 5.3.0 32bit2。