在地图中插入std :: string和共享指针

时间:2015-06-20 13:44:10

标签: c++ c++11 dictionary singleton

我正在使用单例设计模式(我不能使用复制构造函数)。

我有一个:

  • Obj.hpp和Obj.cpp文件
  • House.hpp和House.cpp文件

Obj类包含Houses的地图,我可以使用字符串搜索房屋。 我甚至无法编译我的Obj.cpp文件,不知道为什么...... :(

错误如下:

  

错误C2676:二进制'<' :'const std :: string'没有定义它   运算符或转换为预定义可接受的类型   操作

[Obj.hpp文件]

#include "house.hpp"

class Obj
{
public:
    Obj();
    virtual ~Obj();
private:
    Obj(const Obj& copy);
    Obj& operator=(const Obj& assign);

    typedef std::map<const std::string, std::shared_ptr<House> > myHouseMap;

    myHouseMap _myHouseMap;

    void InitObj ();
}

[Obj.cpp文件]

#include <map.h>
#include <string.h>
#include "Obj.hpp"

Obj::Obj()
{
    InitObj ();
}

void Obj::InitObj ()
{
    /* ERROR ON THIS LINE BELLOW */
    _myHouseMap.insert(std::pair<const std::string, std::shared_ptr<House>>("apartment", new House("apartment")));

}

[House.hpp文件]

class House
{
public:

    House(const char* name);
    virtual ~House();

private:
    House(const House& copy);
    House& operator=(const House& assign);
};

1 个答案:

答案 0 :(得分:1)

不确定您使用的是哪个版本的Visual Studio,但至少Visual Studio 2013似乎没问题:

#include <map>
#include <string>
#include <memory>

class House
{
public:

    House(const char* name);
    virtual ~House();

private:
    House(const House& copy)
    {
    }
    House& operator=(const House& assign)
    {
    }
};

class Obj
{
public:
    Obj()
    {
        InitObj();
    }
    virtual ~Obj();
private:
    Obj(const Obj& copy);
    Obj& operator=(const Obj& assign);

    typedef std::map<const std::string, std::shared_ptr<House> > myHouseMap;

    myHouseMap _myHouseMap;

    void InitObj()
    {
        // Use std::make_shared to create a new std::shared_ptr
        _myHouseMap.insert(std::pair<const std::string, std::shared_ptr<House>>("apartment", std::make_shared<House>("apartment")));
    }
};

问题是对构造函数需要std::shared_ptr而不是原始指针。

相关问题