【问题标题】:C++ class [ ] operator weird outputC++ 类 [ ] 运算符奇怪的输出
【发布时间】:2020-07-30 14:45:45
【问题描述】:

在下面的代码中,我输入了一个字符串向量,它应该是一个消息列表。然后 [ ] 运算符应向我返回指定的消息。例如,如果我输入:

vector<string> m = {
    "Element 0",
    "Attack - at - midnight",
    "Element 2"};

通过说进入以下课程:SelfDestructingMessage sdm(m); ,那么sdm[1]; 应该返回"Attack - at - midnight"。但是,我得到的回报是"\xA0\xABO\xF2\x98U\0\0 at - midnight"。任何正确方向的提示将不胜感激!

class SelfDestructingMessage { // This is my class, fairly straight forward
    private:
        vector<string> messages_;
    public:
            // Constructor
        SelfDestructingMessage(vector<string>);
            // Getter
        vector<string> messages() const {return messages_;}
            // Overloaded Operator
        string const& operator[](size_t);
}

SelfDestructingMessage::SelfDestructingMessage(vector<string> messages){ // Constructor
    messages_ = messages;
}

string const& SelfDestructingMessage::operator[](size_t index){ // Having trouble here
    long signed_index = index;
    string const& message = messages().at(signed_index);
    return message;
}

【问题讨论】:

  • vector&lt;string&gt; const &amp; messages(void) const
  • 这并没有解决问题,但是与signed_indexoperator[] 中的小舞是多余的。整个函数体可以简单地是return messages_[index];。如果你也想提供checked访问,使用SelfDestructingMessage::at(),这样接口与标准库一致。
  • 感谢您的反馈!但是,此代码适用于我的编程课程,并且 [ ] 运算符还有更多内容我没有包括在内,因为它与我的问题无关

标签: c++ string class operators c++17


【解决方案1】:

messages 函数返回向量的临时副本。这个临时向量将在表达式 messages().at(signed_index) 完成后立即结束其生命周期,从而使对其中元素的所有尊重都无效。

您的messages 函数需要返回对向量的引用:

vector<string> const & messages(void) const;

【讨论】:

  • 谢谢,这很有意义!但是,在替换函数后,我得到了一个错误:Undefined symbols for architecture x86_64: "SelfDestructingMessage::messages() const", referenced from: SelfDestructingMessage::operator[](unsigned long) in self_destructing-b14d93.o
  • 没关系,我明白了!非常感谢,非常感谢
猜你喜欢
  • 2019-11-17
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
  • 2016-06-20
  • 1970-01-01
  • 2012-10-23
  • 2021-12-03
  • 2011-06-14
相关资源
最近更新 更多