Why won't return string & from const method compile?

Given the following code:

#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;
}

The compiler presents: "invalid initialization of reference of type 'std::string&' from expression of type 'const std::string'" Why can't I return "m_first" from getName ()? I thought the const at the tail of the function states that the function will not change 'this' ... but I am not trying to change this, just return the data item.

+5
source share
5 answers

const mutable const. , non-const std::string ( ) const std::string, ( const), , .

+15

, , , , , ... , - - , . , , "" , . - (.. ), -. ,

const string& getName() const {return m_first;}

string getName() const { return m_first; } //copies m_first and returns the copy
+6

promises, m_name, , . , , const & .

" " m_name.

. : ++

+4
source

When you return string &, it allows you to change the member of the class ... but the function const, therefore, to resolve this situation is not allowed. But when you return const string &, it does not allow changing the instance of the class.

+2
source

What if you call A.getName().ModifyTheString()==>, it means that you changed this.

+1
source

All Articles