我正在尝试从 C++ STL 实现映射,如下所示:
#include <string>
#include <iostream>
#include <map>
using namespace std;
#include "assembler.h"
// This Class makes use of the Map Template from the Standart Template Library
// All addresses are stored as numerical (Dec) integers
SymbolTable::SymbolTable() { // Constructor
map <string, int> symbolTable;
int address = 0;
}
void SymbolTable::addEntry(string symbol, int address) {
symbolTable[symbol] = address;
address++;
}
// Returns true if symbolTable already contains symbol
bool SymbolTable::contains(string symbol) {
if (symbolTable.find(symbol) == symbolTable.end()) { return true; }
else { return false; }
}
int SymbolTable::getAddress(string symbol) {
return symbolTable[symbol];
}
我尝试用
c++ *.cpp -0 assembler.out
我收到以下错误消息:
symboltable.cpp:57:9: error: no viable conversion from 'mapped_type' (aka 'std::basic_string<char>') to 'int'
return symbolTable[symbol];
^~~~~~~~~~~~~~~~~~~
1 error generated.
我在网上搜索了这个错误,我得到的只是与 STL 相关的错误报告,我无法弄清楚这些报告是否与我遇到的问题相同,如果是,如何解决它。难道我做错了什么?
我已经尝试(可能是愚蠢地)将违规行键入为
return (int) symbolTable[symbol];
感谢您的任何帮助。
我的头文件将类声明为:
class SymbolTable {
public:
SymbolTable();
void addEntry(string, int);
bool contains(string);
int getAddress(string);
private:
map <string, string> symbolTable;
int address;
};