[英]Accessing class members that are arrays through “pointers to class members”
[英]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)”檢索 Thing 插入的 Thing->item 的相同實例,該實例使用鍵“i = 3”調用“addItemToMap”)?
class 架構有點令人困惑,但在您的情況下,您可以像這樣重寫代碼,它將是同一個實例:
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;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.