我有一个包含 map 的父类,而我用来继承该类的子类由于某种原因无法访问 map ,我不明白为什么,我想访问其中的值 map 。
我的代码如下
//HEADER FILE
#include <iostream>
#include <map>
using namespace std;
//////PARENT CLASS
struct TTYElementBase
{
//some code here
};
class element
{
public:
std::map<char,std::string> transMask;
std::map<char,std::string>::iterator it;
void populate();
};
//////CHILD CLASS .HPP
class elementV : public element
{
public :
std::string s1;
std::string s2;
elementV();
friend ostream &operator<< (ostream &, const elementV &);
void transLateMask();
};
//CPP FILE
#include "example.h"
#include <iostream>
elementV::elementV()
{
}
void elementV::transLateMask()
{
for ( it=transMask.begin() ; it != transMask.end(); it++ )
cout << (*it).first << endl;
}
int main()
{
elementV v;
v.transLateMask();
}
// ' OUTPUT IS NOTHING I DONT KNOW WHY?'
输出什么都没有,但我需要从父类访问映射,我做错了什么?
任何帮助我将不胜感激
谢谢
最佳答案
map 是否包含 'D'
的条目当你调用transLateMask()
?如果没有,你会得到未定义的行为(可能是运行时错误),因为你没有检查 find()
的结果。 .这样的东西会更健壮:
auto found = transMask.find('D');
if (found == transMask.end()) {
// handle the error in some way, perhaps
throw std::runtime_error("No D in transMask");
}
std::string str = found->second;
(如果您不使用 C++11,则将 auto
替换为完整类型名称 std::map<char,std::string>::const_iterator
)。
或者,C++11 添加一个 at()
抛出 std::out_of_range
的方法如果找不到 key :
std::string str = transMask.at('D')->second;
关于c++ - 映射继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8839099/