【问题标题】:compiler reports const instead of const&编译器报告 const 而不是 const&
【发布时间】:2022-11-03 13:00:29
【问题描述】:

尝试编译以下代码,无法理解错误消息。

#include<iostream>
#include<string>
using namespace std;
struct S {
    string a{"abc"};
    const string& data() { return a; }
};
int main() {
    S s;
    int a = s.data(); // error: no viable conversion from 'const std::string' to 'int'
    return 0;
}

问题:为什么编译器说 'const std::string' 而不是 'const std::string&'?

尝试使用 Apple clang 14.0.0 和 g++ 12,同样的错误消息。

【问题讨论】:

    标签: c++


    【解决方案1】:

    data() 返回一个参考const std::string 对象,是的。但是,您并没有将引用本身转换为int,而是在转换它所引用的std::string 对象。这就是错误消息不包含&amp; 的原因。

    【讨论】:

      猜你喜欢
      • 2016-05-29
      • 2015-12-28
      • 2019-04-20
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多