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.
"invalid initialization of reference of type 'std::string&' from expression of type 'const std::string'"
const mutable const. , non-const std::string ( ) const std::string, ( const), , .
mutable
const
std::string
const std::string
, , , , , ... , - - , . , , "" , . - (.. ), -. ,
const string& getName() const {return m_first;}
string getName() const { return m_first; } //copies m_first and returns the copy
promises, m_name, , . , , const & .
" " m_name.
. : ++
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.
string &
const string &
What if you call A.getName().ModifyTheString()==>, it means that you changed this.
A.getName().ModifyTheString()
this