C++ include statement required if defining a map in a headerfile.
- by Justin
I was doing a project for computer course on programming concepts. This project was to be completed in C++ using Object Oriented designs we learned throughout the course. Anyhow, I have two files symboltable.h and symboltable.cpp. I want to use a map as the data structure so I define it in the private section of the header file. I #include <map> in the cpp file before I #include "symboltable.h".
I get several errors from the compiler (MS VS 2008 Pro) when I go to debug/run the program the first of which is:
Error 1 error C2146: syntax error : missing ';' before identifier 'table' c:\users\jsmith\documents\visual studio 2008\projects\project2\project2\symboltable.h 22 Project2
To fix this I had to #include <map> in the header file, which to me seems strange.
Here are the relevant code files:
// 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.
};
and
// 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.
}