【问题标题】:how to accessing/Updating a map in some header file from another file/class如何从另一个文件/类访问/更新某个头文件中的映射
【发布时间】:2026-01-16 12:35:01
【问题描述】:

我有几个班级,想访问/更新其中一个班级的地图。 我是 C++ 的新手,我很难弄清楚如何实现这一目标...... 基本上,它正在添加工作(这里它只是一个字符串,但实际上就像我正在使用字符串中的数据创建一个对象(如标记化)并且需要将该对象作为键保存到帧映射中作为值。

paint_service.h

namespace Hello {
namespace World {

class PaintService {
    public:
        PaintService();
        void start_painting(...);
    private:
        **map<string, string> d_frames;**
}; }}

paint_service.cpp

namespace Hello {
namespace World {
PaintService::PaintService() { }
void PaintService::start_painting(...) {
    PaintDistributer paint_distributer;
    //works = ... assuming there's this works is like vector of string
    for(String work: works) {
        paint_distributer.distribute(work);
    }
}
}}

paint_distributor.cpp

namespace Hello {
namespace World { 
...
Event PaintDistributer::distribute(const string& work) {
   string work_type = work.substring(3,5);
   if (work_type == "framing") {
        **// I wanna add this "work" to the map, d_frames in PaintService, how can I do this?**
        return Event(something(work))
   }
} }}

谢谢!

【问题讨论】:

  • 所以你返回的不是你想要插入的?
  • @Surt 是的,我正在返回其他类型的事件,这里不包括在内。添加到地图只是我希望在返回之前处理的逻辑的一部分。
  • 所以在 PaintService 中构造的 PaintDistribute 必须引用 PaintService 以便您可以在那里添加到地图。
  • string work_type = work.substring(3,5); 将返回最多 5 个字符的字符串,因此它永远不会等于 "framing"。我还建议改写namespace Hello::World {

标签: c++ class dictionary


【解决方案1】:

一种可能的解决方案(未经测试的代码)。

PaintService添加

void Add(string key, string value) {
  d_frames[key] = value;
}

在对start_painting 的调用中添加对拥有实例的引用。

PaintDistributer paint_distributer(*this); // constructor needs a reference owner

并在分发中添加

if (work_type == "framing") {
  owner.Add("distributor", work_type); // or what you want to register.
}

【讨论】: