【发布时间】:2011-08-29 13:24:37
【问题描述】:
给定以下代码:
#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;
}
编译器显示:"invalid initialization of reference of type 'std::string&' from expression of type 'const std::string'"
为什么我不能从 getName() 返回 "m_first" ?我认为函数尾部的 const 表明该函数不会更改 'this'……但我并没有尝试更改 this ,只是返回一个数据成员。
【问题讨论】:
标签: c++ string reference constants