c++ - C++:将字符串指针设置为常量字符串值
问题描述
基本上我需要创建一个包含 id 和键的元素。id 和 key 的私有值分别是 string* 和 int。
Element::Element(const string & id, int key) {
this->id = id;
this->key = key;
}
设置时,我显然遇到了问题。
cannot convert ‘const string {aka const std::__cxx11::basic_string<char>}’ to ‘std::__cxx11::string* {aka std::__cxx11::basic_string<char>*}’ in assignment
this->id = id;
所以我想知道如何设置它,使我的私有成员 id 等于 const 字符串 & id。
编辑:澄清一下,让这些值成为字符串指针和 const 字符串不是我的决定。由于我无法理解的原因,这只是项目的一部分。
解决方案
你可能想这样写你的类:
class Element {
std::string id; // Should these be const?
int key;
public:
Element(const string &id, int key): id(id), key(key) {}
};
这就是全部Element
吗?然后你就可以写了using Element = std::pair<const std::string, int>
。或者,如果您将元素添加到容器中,例如 astd::vector
或std::set
,那么您可以避免创建新类而只使用 a std::map<const std::string, int>
。
推荐阅读
- matlab - 如何在matlab的for循环中向地图添加值?
- .net - 在终端中调试 dotnet 核心程序
- python - 计算 txt 文件中每一行的出现次数并将它们保存到 Python 中的矩阵中
- javascript - Java 脚本闭包 - 本地绑定结果不是我所期望的
- angular - 如何在猫鼬的查询中应用?
- getdate - 如何在 SSRS 中使用 getdate() 而不包括周末和节假日
- php - 如何根据用户使用 PHP 的操作来增加变量
- python - 如何根据嵌套字典中的子值计算父字典值
- python - Matplotlib 绘制不同颜色的多边形
- c# - 自动映射器根据枚举值映射某些布尔属性