继承可以't访问地图

Inheritance can't access map

本文关键字:访问 地图 继承      更新时间:2023-10-16

我似乎无法从子类访问父类中的映射,因为我试图输出映射的内容,但没有显示任何内容。

下面我添加了完整的代码,总的来说,如果我在transLateMask()中填充地图,它会打印出内容,但是如果我在POPULATE()中添加地图,它不会打印出任何内容,我不知道为什么?

这是我的密码。

//HEADER FILE
//////PARENT CLASS
#include <iostream>
#include <string>
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"
elementV::elementV()
{
}
void element::populate()
 {
    transMask['D']='D'; //WILL PRINT OUT NOTHING IF I POPULATE HERE 
 }

void elementV::transLateMask()
{
    for ( it=transMask.begin() ; it != transMask.end(); it++ )
        std::cout << (*it).first << std::endl;
}
int main()
{
    element e;
    e.populate();
    elementV v;
    v.transLateMask();
}

它什么都不输出——为什么?

对e.populate()的调用填充e.transMask,而不是v.transMask。您需要调用v.populate)。

我认为您没有include指令#include <string>

也用#include <string> 替换#include <string.hpp>

然后,您可以选择添加using namespace std;,这样您就不必在整个上使用std::限定符