What should we use then?
MyString& const ref = obj;OR
MyString const &ref = obj;
/******************************************************** A reference Example ********************************************************/ #include <iostream> using namespace std; class MyString{ public: MyString(const string& str); ~MyString(); void printString() const; private: MyString(); MyString(const MyString&); string m_str; }; MyString::MyString(const string& str){ m_str = str; } MyString::~MyString(){ } void MyString::printString() const { cout << m_str; cout << endl; } int main(){ MyString pStr("P"); MyString qStr("Q"); MyString rStr("R"); MyString sStr("S"); // refStr is a reference to pStr MyString &refStr = pStr; refStr.printString(); pStr.printString(); // refStr is assigned value at qStr but reference // still points to pStr refStr = qStr; refStr.printString(); pStr.printString(); qStr = rStr; // refStr value remains unchanged refStr.printString(); pStr.printString(); pStr = sStr; // refStr being reference to pStr, it's value is changed // as pStr value is changed refStr.printString(); pStr.printString(); return 0; }
In the following example, reference itself is a 'const' and is pointing to the data which is not. The code compiles successfully in Microsoft Visual Studio and refStr value is allowed to change but in GCC, throws the error: `const' qualifiers cannot be applied to `MyString&'
MyString& const refStr = pStr; //
In this case the safest solution is to declare reference to the 'const' value as follows
MyString const &refStr = pStr;
OR
const MyString &refStr = pStr;
The compiler will an error whenever the 'const' value pointed by refStr is changed.
refStr = qStr;
// throws an error if MyString const &refStr = pStr;
//OR
//const MyString &refStr = pStr;
No comments:
Post a Comment