尝试通过指针映射访问类成员

Trying to access class members through a map of pointers

本文关键字:访问 成员 映射 指针      更新时间:2023-10-16

我有以下代码:

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;
};