c++ - 为什么从 const 方法返回的 string& 无法编译?

标签 c++ string reference constants

给定以下代码:

#include <iostream>
#include <string>
using namespace std;

class A
{
private:
    string m_name;
    string m_first;
public:
    A(): m_first("string") {}
    virtual void print() const {}
    string& getName() const {return m_first;}  // won't compile 
    const string& getLastName() const {return m_name;}  // compile
};


int main()
{
    A a;
    return 0;
}

编译器显示:“从‘const std::string’类型的表达式中无效初始化‘std::string&’类型的引用” 为什么我不能从 getName() 返回“m_first”?我认为函数尾部的 const 表示函数不会更改“this”...但我并没有尝试更改 this,只是返回一个数据成员。

最佳答案

因为在 const 方法内部,所有非 mutable 成员都是隐式的 const。因此,您尝试将对非 const std::string(您的返回值)的引用绑定(bind)到 const std::string 类型的对象,即非法(因为它允许修改 const 数据),因此出现错误。

关于c++ - 为什么从 const 方法返回的 string& 无法编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7230722/

相关文章:

r - 连接字符串/字符向量

c++ - 在 C++ 中通过引用选项传递

c++ - 我无法理解这种复制构造函数的行为

c++ - C++ 中的对象变量保存值,而不是对象引用

c++ - 什么是友元说明符的析构函数?

c++ - 尝试使用 opencv c++ 绘制简单函数

c++ - MPI_Allreduce 中的 fatal error

c++ - 用Qt显示大量图像

非英文字符的 string.sub 问题

C 在传输之前将 char* 转换为网络字节顺序