从概念上讲,我有一门课可以做到这一点。请注意,底层数据类型在实际应用程序中更为复杂。这只是为了简化:
class A
{
private:
std::map<std::string, int> database;
public:
bool knowsValue(std::string string_id); // Returns true if string_id is in database
const int& getValueA(std::string string_id); // Returns reference to int mapped to string_id in database
}
因为为未知数调用 getValueAstring_id会导致错误,所以通常同时调用这两个命令:
if obj.knowsValue(string_id)
int val = obj.getValueA(string_id)
else
std::cout << "Value does not exist in database";
find因为这需要对数据库对象进行两次后续操作,所以我制作了这个函数bool getValueB(std::string string_id, int& val),如果在数据库中则返回 true string_id,并将映射的值分配给val.
这两个getValue函数的内容几乎相同,所以我想getValueB在getValueA. 这是我超出我的深度的地方,通过这种尝试:
const int& getValueA2(std::string string_id)
{
static int val_tmp; // If not static, this object is deleted after the function call and the reference becomes invalid
if (getValueB(string_id, val_tmp))
return static_cast<const int&>(val_tmp);
else
return static_cast<const int&>(0);
}
显然static关键字在这里是不合适的,因为值不应该在函数之间共享。const此外,参考不在的事实getValueB也是次优的。
我的问题:
- 什么是正确的编写方法
getValueA2,它试图返回它在参数中获得的引用?中间val_tmp看起来很恶心。 - 引用可以
const在这个结构中吗?
我倾向于改变getValueB以const int& getValueB(std::string string_id, const bool value_exists_in_db)解开这个混乱,但我有兴趣找出什么是可能的以及我哪里出错了。
编辑:请注意const int& getValueA(std::string string_id),理想情况下,不应更改的声明以避免更改代码库的其余部分。