[英]C++ error: no viable conversion from 'mapped_type' to 'int'
I am trying to implement the a map from the C++ STL as follows: 我正在尝试从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];
}
I try to compile this with 我尝试用
c++ *.cpp -0 assembler.out
and I get the following error message: 我收到以下错误消息:
symboltable.cpp:57:9: error: no viable conversion from 'mapped_type' (aka 'std::basic_string<char>') to 'int'
return symbolTable[symbol];
^~~~~~~~~~~~~~~~~~~
1 error generated.
I have searched for this error online and all I get is bug reports relating to the STL and I cannot figure out if those reports are the same problem I am having and if so how to get around it. 我已经在网上搜索了此错误,并且得到的只是与STL相关的错误报告,我无法弄清楚这些报告是否与我遇到的问题相同,以及如何解决该问题。 Am I doing something wrong? 难道我做错了什么?
I have tried (probably stupidly) to typecast the offending line as 我已经尝试过(可能是愚蠢的)将违规行类型转换为
return (int) symbolTable[symbol];
Thank you for any help. 感谢您的任何帮助。
My header file declares the class as: 我的头文件将类声明为:
class SymbolTable {
public:
SymbolTable();
void addEntry(string, int);
bool contains(string);
int getAddress(string);
private:
map <string, string> symbolTable;
int address;
};
This: 这个:
SymbolTable::SymbolTable() { // Constructor
map <string, int> symbolTable;
^
^
is a function-local variable, not a member variable. 是函数局部变量,而不是成员变量。 It is not the same as the symbolTable
that you're accessing in eg getAddress
, which presumably is a member variable. 它与您在例如getAddress
访问的symbolTable
,它可能是成员变量。 You haven't shown the class body, but my guess is that it's defined differently. 您尚未显示类主体,但我想它的定义有所不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.