[英]Why return string& from a const method won't compile?
给出以下代码:
#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'"
stst "invalid initialization of reference of type 'std::string&' from expression of type 'const std::string'"
为什么我不能从getName()返回“m_first”? 我认为函数尾部的const表示该函数不会改变'this'...但我不是要改变它,只是返回一个数据成员。
因为在const方法中,所有非mutable
成员都是隐式const
。 所以,你想以非const的引用绑定std::string
(你的返回值),以类型的对象const std::string
,这是非法的(因为它允许常量数据的修改),因此,错误。
通过返回引用,您说您可以修改引用变量隐式指向的类数据成员,因此修改类...但您已将类方法专用于常量方法,这意味着它不是允许更改任何未明确声明为mutable的类成员变量。 因此,通过返回非常量引用,您将破坏类接口已建立的封装“契约”。 您可以选择返回临时对象(即创建对象副本)或常量引用。 所以你可以做到
const string& getName() const {return m_first;}
要么
string getName() const { return m_first; } //copies m_first and returns the copy
change it. 您的代码承诺引用不会更改m_name成员,但您返回更改它的引用。 你想要的是一个字符串const和返回类型。
这将返回对m_name的“只读”引用。
另请参阅: 关于const正确性的C ++ FAQ
当你返回string &
,它允许修改类成员...但是函数是const
,所以不允许这样的情况。 但是当你返回const string &
,它不允许修改类实例。
如果你调用A.getName().ModifyTheString()
==>这意味着你修改了this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.