C ++:将字符串指针设置为const字符串值

时间:2018-10-22 21:53:08

标签: c++

基本上,我需要创建一个包含id和key的Element。 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字符串不是我的决定。出于我无法理解的原因,这只是项目的一部分。

4 个答案:

答案 0 :(得分:4)

您可能想像这样编写您的课程:

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>。或者,如果要将元素添加到std::vectorstd::set之类的容器中,则可以避免创建新类,而只需使用std::map<const std::string, int>

答案 1 :(得分:2)

这是因为您正在分配对指针的引用。将地址分配给指针,并保留constnes,“ id”应为指向const的指针:

const std::string* id;

和作业:

this->id = &id;

这是解释。另一件事是,如果删除处理的对象,这可能导致指针悬空。

答案 2 :(得分:1)

您正在尝试将std::string const&分配给变量std::string*。 这很像试图保存一个值来代替指针。 可能的解决方案是:

this->id = new std::string(id);

它将复制id并将其存储为成员。但是请确保事后清理资源。 但是我不推荐这种解决方案。您真的需要将成员存储为指针吗?

如果连接的字符串永远不会更改(在构造函数中仅分配一次),则使用引用是更好的解决方案:

... //member definitions
std::string const& id;
...

然后,在构造函数中,您需要指定id:

...
Element::Element(/*Params*/) : id(id) {
...

如果不合适,可以将成员字符串存储为值,那么您就不必担心以后清理指针了。


快速补充一点,使用“原始”指针通常是不好的做法。如果绝对必须使用指针(不能用引用或值代替),则最好使用std::unique_ptrstd::shared_ptr,因为它们可以防止资源泄漏。


要编辑的答案: 如果无法在此处摆脱“指针”,则需要确定是否需要访问对最初作为ID传递的字符串的更改。 如果是,那么最好在初始ID超出范围后使用Mateusz Wojtczak的答案,它可能存在指针问题。 如果不是,只需使用new进行显式复制。只是不要忘记在析构函数中delete

答案 3 :(得分:1)

class Element {
private:
    std::string id; // <- not a pointer
    int key;
public:
    Element(const string& Id, int Key) :
        id(Id),
        key(Key)
    {}
};