我想在一個返回一個常量指針映射的類中創建一個函數。然後在另一個類中,我可以有一個函數,它可以接受常量指針,聲明迭代器,並將映射的內容複製到一個向量中。這個地圖類到矢量類是練習的要求。我從來沒有做過映射ptrs之前,我沒有編譯器喜歡的語法。這裏是我的地圖函數聲明:通過返回一個指針來訪問地圖C++
class WordCount
{
public:
WordCount();
~WordCount();
void word_insert(std::string clean_word);
void print_all();
const std::map<std::string, int> * get_map();
private:
std::map<std::string, int> m_word_counts;
std::map<std::string, int>::iterator m_it;
std::pair<std::map<std::string, int>::iterator, bool> m_ret;
};
但是當我嘗試將其定義爲這樣的(或許多變化我都試過)函數,我得到一個轉換錯誤。以下需要改變的是什麼?
const map<string, int > * WordCount::get_map()
{
const map<string, int > *ptr = m_word_counts;
return ptr;
}
-
爲什麼指針?爲什麼不只是返回一個參考? –