【发布时间】:2013-12-05 15:09:53
【问题描述】:
我在通过数组订阅和分配获得所需行为时遇到问题。
有没有办法判断赋值是否与数组订阅一起使用?
编辑 我的问题可能应该是,我可以将 [] 映射到 getter,并将 []= 映射到 setter
// Expect this to return a reference to the value if the key exists,
// or throw an exception if not
myMap["Key"];
// Expect this to always return a reference to the value
// so the value can be populated
myMap["Key"] = "Value";
// The method being used
template <typename K, typename V>
V& MyMap<K, V>::operator[](const K &key)
{
if(this->keyExists(key))
{
return this->find(key);
}
else
{
// At this point I'd like to throw an exception if
// assignment is not being used
this->insert(key, NULL);
return this->pairs[this->itemsStored].val;
}
};
【问题讨论】:
-
这是一个数组还是
std::map? -
myMap的类型是什么? -
这是我自己的地图实现,可惜不能使用std::map
-
std::map不区分,所以我不会费心尝试自己做。您可以通过返回一个临时对象来跳过燃烧的箍,如果它的operator =尚未被调用(尽管您不应该从析构函数中抛出)并且该对象具有到值类型的隐式类型转换,则该对象会在销毁时引发异常。 .. 但我宁愿接受 C++ 不区分读取和写入operator[]。 -
@JohnKugelman :你可以制作
const和非const版本的operator[]......但这可能比它的价值更麻烦。