C++ 返回指向在堆上创建的对象的成员的指针

C++ 返回指向在堆上创建的对象的成员的指针,c++,pointers,object,rvalue,C++,Pointers,Object,Rvalue,如果我有课 class Item { public: Item(int key, int value):key(key), value(value) {} int GetValue() { return value; } private: int key; int value; } 如果在堆上创建项对象: Item *item = new Item(1, 2); 是否可以获取指向此对象的值成员的指针 例如,我有另一个类中的另一个方法 int* GetValue

如果我有课

class Item {
 public:
  Item(int key, int value):key(key), value(value) {}
  int GetValue() {
    return value;
  }
 private:
  int key;
  int value;
}
如果在堆上创建项对象:

Item *item = new Item(1, 2);
是否可以获取指向此对象的值成员的指针

例如,我有另一个类中的另一个方法

int* GetValue(int k) {
  Item* item = ...;  // It finds the pointer to an Item object with key k that was created before.
  // Is there anyway I can return the pointer to the value member of this item?
 // Something like:
 return &(item->GetValue());  // This won't compile because item->GetValue() is a r-value. Is there any alternative way to walk around?
}

尝试将这些代码行添加到您的代码中

template <class Tag, typename Tag::type Value>
struct Getter
{
    friend typename Tag::type get(Tag) {
        return Value;
    }
};

struct Tag_item {
    typedef int Item::*type;
    friend type get(Tag_item);
};

int* GetValue(int k) {
    static Item item(13, 14);
    // std::cout << item.GetValue() << std::endl; // This line to test output.
    return &(item.*get(Tag_item())); // If pItem is pointer then pItem->*get(Tag_item())
}
template struct Getter<Tag_item, &Item::value>;
模板
结构吸气剂
{
好友typename标记::键入get(标记){
返回值;
}
};
结构标记项{
typedef int项::*类型;
好友类型get(标记项);
};
int*GetValue(int k){
静态项(13,14);

//std::不能使用Map来存储键和值。实际上我正在尝试实现一个哈希映射,所以我不能使用现有的库。