c++ - 映射继承

标签 c++ inheritance dictionary

我有一个包含 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/

相关文章:

javascript - 将js数组转换为字典映射

c++ - STL有什么了不起的?

c++ - emplace_back 导致静态 constexpr 成员上的链接错误

c# - 是否有访问 C++ native COM 函数以从 C# 互操作的最佳实践?

python - 合并字典列表中的键

python - 如何用 Python 将字典写入 Excel

c++ - 何时在 C++ 中使用 __declspec(dllexport)

c# - 从类继承并添加附加属性

c++ - 使用模板实现多态

c++ - 使用虚拟继承对多态类使用 Cereal 进行序列化