给定以下代码:
#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/