gpt4 book ai didi

c++ - 在 map 中插入 std::string 和指向对象的共享指针

转载 作者:行者123 更新时间:2023-11-30 05:41:55 28 4
gpt4 key购买 nike

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

我有一个:

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

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

错误如下:

error C2676: binary '<' : 'const std::string' does not define this operator or a conversion to a type acceptable to the predefined operator

[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);
};

最佳答案

不确定您使用的是哪个版本的 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 而不是原始指针。

关于c++ - 在 map 中插入 std::string 和指向对象的共享指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30954660/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com