在类中使用映射并通过其他类的 get() 和 set() 函数访问值
Using maps inside class and accessing values via get() and set() functions from other class
>我无法使用在头文件中定义的此映射添加值作为类成员函数的受保护属性。
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));
}
相关文章:
- C++中是否有任何函数等同于python中字典的get函数?
- 如何将 c++ get 函数代码转换为 opencv 算法中使用的 python
- 使用"push_back"作为带有"get"函数C++的向量
- c++ 在类中声明私有的向量,但有一个 get 函数
- C++ :: 设置值函数在函数内设置,但后跟 Get 函数,设置值消失了
- get 函数返回无效值
- 通过引用将私有类实例传递到另一个类 C++ 的"get"函数中
- 如何允许编译器推断出正确的返回类型以进行模板get函数
- 由值持有的成员的get函数应该具有什么类型
- 无法返回带有 get 函数的对象数组
- 返回get函数中的值
- friend get 函数,返回通过可变参数模板递归计算的类型
- 带有get函数的模板类始终返回参考
- 在 xcode 中使用 get 函数时面临问题
- 回到c++,带指针的void函数,如何生成get函数
- 如何在 C++ 代码中使用 GET 函数
- 继承的'Get'函数不会返回正确的值
- 使用 get 函数访问存储在节点中的数据
- C++:将'this'指针与"get"函数一起使用以替换 cout 语句的可能性
- 如何在C++中操作get函数中的数据