2
婁我提供很簡單的東西,我正在掙扎的完整代碼..C++如何將對象添加到地圖和新創建的對象返回內部地圖參考
- 我需要創建一個地圖字符串和對象...
- 當請求,如果字符串是地圖裏面,我需要一個 參考返回一個對象可在地圖
- 內。當字符串不是地圖裏面,我需要創建對象, 與該字符串並返回(如前)對新的參考 創建對象
請檢查下面的兩條評論我說「錯誤」,看看問題出在哪裏。
我的問題是:
- 我如何可以插入到地圖,一個對象? InitObj()上的行 有什麼問題?
- 如何創建返回對象的引用,我只是在地圖上創建了 ?截至getHouse()函數提前
由於年底:)
#include <map>
#include <string>
#include <memory>
class House
{
public:
House(const char* name) : _name(name) {};
~House() {};
std::string getHouseName() { return _name; }
private:
std::string _name;
House(const House& copy)
{
}
House& operator=(const House& assign)
{
}
};
class Obj
{
public:
Obj()
{
InitObj();
}
~Obj() {};
House& getHouse (const char *houseName)
{
std::string name = houseName;
auto i = _myHouseMap.find(name);
//this string doesn't exist on map? then create a new house and add to the map and return the reference to it
if (i == _myHouseMap.end())
{
//create a new house
House h(houseName);
//add to the map
_myHouseMap.insert(std::pair<const std::string, House>(houseName, h));
//return the reference to the house created
return h; //<--- ERROR!!!! need to return the reference!
}
return (i->second);
}
private:
Obj(const Obj& copy);
Obj& operator=(const Obj& assign);
typedef std::map<const std::string, House> myHouseMap;
myHouseMap _myHouseMap;
//the initialization will add one object to my map
void InitObj()
{
House h("apartment");
_myHouseMap.insert(std::pair<const std::string, House>("apartment", h)); //<--- ERROR see reference to function template instantiation 'std::pair<_Ty1,_Ty2>::pair<const char(&)[10],House&>
}
};
int main(void)
{
Obj aaa;
House& myHouse1 = aaa.getHouse ("apartment");
std::cout << "House is " << myHouse1.getHouseName();
House& myHouse2 = aaa.getHouse ("newHouse"); //here a new house must be created and added to the map
std::cout << "House is " << myHouse2.getHouseName();
return 0;
}
謝謝巴里。但我仍然有同樣的錯誤...我需要返回一個參考... 錯誤:請參閱函數模板實例化參考'std :: pair <_Ty1,_Ty2> ::對 –
waas1919
@ waas1919將返回一個參考。 – Barry