尝试通过指针映射访问类成员
Trying to access class members through a map of pointers
我有以下代码:
class Thing
{
private:
Item item;
};
class Mgr{
public:
std::map<int, Item*> sps;
};
void Thing::addItemToMap(std::map<int, Item*>& sps, int i){
sps.insert(std::make_pair(i, &(this->item)));
}
void Mgr::accessItem( int i){
auto it = sps.find(i);
if(it!=sps.end(){
// it->second is the instance of Item I inserted in the map before?
}
}
Mgr 是否有可能通过"accessItem(3("方法检索事物插入的同一>实例,调用键为"i = 3"的"addItemToMap"?
这有点令人困惑的类架构,但在你的情况下,你可以像这样重写你的代码,它将是同一个实例:
class Item final {
public:
// Some data
int data{ 0 };
};
using ItemsMap = std::map<int, std::shared_ptr<Item>>;
class Thing final {
public:
void addItemToMap(int i, ItemsMap& items)
{
items.insert(std::make_pair(i, _item));
}
private:
std::shared_ptr<Item> _item;
};
class Mgr final {
public:
void accessItem(int key)
{
ItemsMap::const_iterator foundIt = sps.find(key);
if (foundIt != sps.end()) {
std::cout << foundIt->second->data << std::endl;
}
}
private:
ItemsMap sps;
};
相关文章:
- C++ 传递指向对象的指针的指针,无法访问成员
- 从不同C++类的成员变量访问成员函数
- 使用 getter 访问成员变量C++
- 如何使用包含内部类的类实例有效地从内部类访问成员?
- 通过多个类访问成员时出错
- 如何在使用对象指针时访问成员函数
- 为什么相应成员不能正确访问成员函数指针
- 从两个不同类继承的非虚拟基类的访问成员
- 如何使用 gcc 内联汇编器代码访问成员变量
- 如何使用常数向量访问成员函数
- 访问成员函数中参数的类成员
- C++嵌套结构初始化和访问成员
- 通过指向班级第一个成员的指针访问成员是不确定的行为吗?
- 如何使用C STD :: SET中的迭代器访问成员功能
- 访问成员C 时,结构的向量生成了范围的错误
- 带指针的班级访问成员
- 从聚合类访问成员变量
- 如何访问成员变量 sqlite 回调
- ctypes/C++segfault访问成员变量
- 通过父类型的指针或直接从派生类访问成员函数的差异