如何修复这些错误:C2146 和 C4430(在 C++ 中)

How to fix these errors: C2146 & C4430 (in c++)

本文关键字:C4430 C++ C2146 何修复 错误      更新时间:2023-10-16

所以,我的老师给了全班这个代码,但我在运行它时遇到了问题。 我得到的错误是C2146和C4430。我尝试通过将包含添加到头文件来弄乱,但我仍然不确定问题是什么。

我已经注释了下面的代码,其中错误由编译器指示。

助理H文件

template<class T> class assoc {
public:
struct pair {
string key;   //error C2146: syntax error: missing ';' before identifier 'key'
T      value; 
pair  *next;  

pair() : key(), value(), next(NULL) {}
pair( const string& key, T value, pair* next = NULL ) //error c4430: missing type specifier - int assumed. Note: c++ does not suport default - int
: key(key), value(value), next(next) {}
};
private:
pair * table;
}

未定义string类型。您需要从std命名空间导入它:

#include <string>
using std::string;

当然,您也可以使用using namespace std;从命名空间导入所有内容,但这通常是一个坏主意 - 对于不像string那样普遍的东西,最好使用限定名称(例如std::pair)。您的代码实际上是一个很好的例子,您的pairusing namespace std会与std中的代码发生冲突。