gpt4 book ai didi

如果在头文件中定义映射,则需要 C++ include 语句

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:00:48 25 4
gpt4 key购买 nike

我正在做一个关于编程概念的计算机类(class)项目。该项目将使用我们在整个类(class)中学到的面向对象设计在 C++ 中完成。无论如何,我有两个文件 symboltable.hsymboltable.cpp .我想使用 map 作为数据结构,所以我在头文件的私有(private)部分中定义它。我 #include <map>在我之前的 cpp 文件中 #include "symboltable.h" .

当我去调试/运行程序时,编译器 (MS VS 2008 Pro) 出现了几个错误,第一个错误是:

Error   1   error C2146: syntax error : missing ';' before identifier 'table'   c:\users\jsmith\documents\visual studio 2008\projects\project2\project2\symboltable.h   22  Project2

为了解决这个问题,我必须 #include <map>在头文件中,这对我来说似乎很奇怪。

相关代码文件如下:

// symboltable.h
#include <map>

class SymbolTable {
public:
SymbolTable() {}
void insert(string variable, double value);
double lookUp(string variable);
void init(); // Added as part of the spec given in the conference area.
private:
map<string, double> table; // Our container for variables and their values.
};

// symboltable.cpp
#include <map>
#include <string>
#include <iostream>
using namespace std;

#include "symboltable.h"

void SymbolTable::insert(string variable, double value) {
table[variable] = value; // Creates a new map entry, if variable name already exist it overwrites last value.
}

double SymbolTable::lookUp(string variable) {
if(table.find(variable) == table.end()) // Search for the variable, find() returns a position, if thats the end then we didnt find it.
throw exception("Error: Uninitialized variable");
else
return table[variable];
}

void SymbolTable::init() {
table.clear(); // Clears the map, removes all elements.
}

最佳答案

我的猜测是您有另一个包含头文件 #include "symboltable.h" 的文件.而那个其他源文件没有 #include <map>也不#include <string>也没有 using namespace std在它包括 "symboltable.h" 之前.

出现错误时检查正在编译的文件。它可能是与您提到的 .cpp 不同的源文件吗?可能是像 main.cpp 这样的东西?

解决问题的另一种方法是将所需的包含放在头文件中并使用 std::map而不是简单的 map .你也用 string这也在命名空间内 std .所以这需要是 std::string .并把缺少的 #include <string> .

关于如果在头文件中定义映射,则需要 C++ include 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2535008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com