【发布时间】:2016-01-14 05:44:37
【问题描述】:
如果我有课
class Item {
public:
Item(int key, int value):key(key), value(value) {}
int GetValue() {
return value;
}
private:
int key;
int value;
}
如果我在堆上创建一个 Item 对象:
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?
}
【问题讨论】:
-
使用 Map 存储 key 和 value。
-
我实际上是在尝试实现一个哈希映射,所以我不能使用现有的库。
标签: c++ pointers object rvalue