首页 > 解决方案 > 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 字符串不是我的决定。由于我无法理解的原因,这只是项目的一部分。

标签: c++

解决方案


你可能想这样写你的类:

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::vectorstd::set,那么您可以避免创建新类而只使用 a std::map<const std::string, int>


推荐阅读