假設我有一個具有兩種方法的類。其中一個應該在容器中找到一個對象並按值返回,另一個應該通過引用返回。當然,我希望第一種方法是const
(this
是const
),第二種方法不是。編寫兩種返回C++中相同項目的值和引用的方法的最佳方法
有沒有一種方法來重新使用這兩種方法之間的代碼,而不引入他們都依賴的第三種方法?下面我給出了這個問題的一個玩具例子,其中人們應該想象find
步驟實際上要複雜得多。
在「可能的實現1」下面,有一個錯誤,由於這樣的事實,我打電話(非const
)get_ref
從內(const
)get_value
。在「可能的實現2」中,引用是從值的臨時副本創建的,這當然是一個主要問題。
在需要const
引用的情況下,當然沒有問題,但假設我實際上需要一個普通引用。
// Header:
#include <string>
#include <map>
using std::string;
using std::map;
class Test {
public:
map< string, string > stuff;
string & get_ref(const string key);
string get_value(const string key) const;
};
// Possible implementation 1:
string Test::get_value(const string key) const {
return get_ref(key);
}
string & Test::get_ref(const string key) {
return stuff.find(key)->second;
}
// Possible implementation 2 (obviously wrong, but here for the sake of pointing that out):
string Test::get_value(const string key) const {
return stuff.find(key)->second;
}
string & Test::get_ref(const string key) {
return get_value(key);
}
想一想在第二次執行中get_ref正在返回什麼。如果你試圖實際編譯*編譯器告訴你什麼? –
在一個不相關的說明中,你還應該考慮如果找不到密鑰並且'find'函數返回'end'迭代器會發生什麼情況。 –
@Someprogrammerdude如果你暗指暫時返回,OP已經提到,作爲不使用第二次執行的原因 –