在类中使用映射并通过其他类的 get() 和 set() 函数访问值

Using maps inside class and accessing values via get() and set() functions from other class

本文关键字:get 函数 访问 set 其他 映射      更新时间:2023-10-16

>我无法使用在头文件中定义的此映射添加值作为类成员函数的受保护属性。

class xyz{
protected:
map < string, string > *tagsMap;

public:
xyz();
//set Tags
void addTag(string _tagName, string _tagValue) const;
}

// In cpp class, 
//set new Tags
void xyz::addTag(string _tagName, string _tagValue) const {
//map < string, string > tagsMap ;
//gives error until I uncomment above line, but thats local map
tagsMap.insert(pair<string, string>(_tagName, _tagValue));
// first insert function version (single parameter):
tagsMap .insert(pair<string, string>(_tagName, _tagValue));
for (auto& t : tagsMap )
cout << "addTag():" << t.first << "=" << t.second << endl;
}

您有 3 个问题:

1(类成员被声明为指针

addTag()里面的注释行:

// map < string, string > tagsMap;

是一个指针,这就是如果您取消注释本地映射声明,它起作用的原因。

但是,这在逻辑上是不正确的,因为它不是类的成员 - 它隐藏了您的tagsMap类成员。

因此,您需要在xyz类中声明tagsMap非指针。

map < string, string > *tagsMap;
//  ^ remove asterisk '*'

2( 类定义后缺少分号

在类定义后添加;分号

class xyz {
...
}
// ^^^ add semicolon here

3( 常量函数

删除addTag()中的const以便能够在类成员上写入tagsMap

void xyz::addTag(string _tagName, string _tagValue) const { .. }
// ^^^^^ remove const
void addTag(string _tagName, string _tagValue) const;
// ^^^^^ remove const

是的,不需要指针。 它在使函数非常量之后工作,如@codekaizer在上面的评论中建议的那样。

class xyz{
protected:
map < string, string > tagsMap;
public:
xyz();
//set Tags
void addTag(string _tagName, string _tagValue);
}

在 cpp 类中,

void xyz::addTag(string _tagName, string _tagValue) {
tagsMap.insert(pair<string, string>(_tagName, _tagValue));
}