【问题标题】:returning a const reference to a string返回对字符串的 const 引用
【发布时间】:2017-06-18 03:17:30
【问题描述】:

我正在构建一个秘密消息类,其中包含消息中的行向量以及每条消息可以查看的最大次数。我正在尝试重载 [] 运算符以便能够看到消息。

例如:如果我想初始化下面的字符串向量,我应该可以这样做......

vector<string> m = {
    "Here is the first line",
    "I have a second line as well",
    "Third line of message"};

//initialize message - each line may be viewed a maximum of two times
SelfDestructingMessage sdm(m, 2);

cout << sdm[0] << endl;
//outputs "Here is the first line" and decrements remaining views of first line by one

我的问题是,我在头文件中声明了操作符,然后在函数文件中定义如下:

string SelfDestructingMessage::operator[](size_t index){
    return const string & message[index];
}

因此,我应该能够使用带有 size_t 参数(索引)的 [] 运算符查看实际消息。它应该返回对从特定于对象的消息向量索引的消息字符串的 const 引用。

但是在编译时,我得到一个“错误:在'const' return const string & message[index];之前的预期主表达式;”

你知道这是什么原因吗?

【问题讨论】:

    标签: c++ operator-overloading


    【解决方案1】:

    const string &amp; 部分需要在函数的签名中。无需在正文中将message[index] 显式转换为const string&amp;,它会自动发生:

    const string& SelfDestructingMessage::operator[](size_t index){
        return message[index];
    }
    // also update the declaration
    

    下次请尝试写minimal, compilable example。它确实对试图回答您问题的人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      相关资源
      最近更新 更多