一个相当理论的问题......为什么常量引用的行为与常量指针的行为不同,我实际上可以更改它们指向的对象?它们看起来像是另一个简单的变量声明.我为什么要用它们?这是我运行的一个简短示例,它编译并运行时没有错误:
int main (){
int i=0;
int y=1;
int&const icr=i;
icr=y; // Can change the object it is pointing to so it's not like a const pointer...
icr=99; // Can assign another value but the value is not assigned to y...
int x=9;
icr=x;
cout<<"icr: "<<icr<<", y:"<<y<<endl;
}
Run Code Online (Sandbox Code Playgroud) 在C++工作了15年后,我发现我完全不理解参考文献......
class TestClass { public: TestClass() : m_nData(0) { } TestClass(int n) : m_nData(n) { } ~TestClass() { cout << "destructor" << endl; } void Dump() { cout << "data = " << m_nData << " ptr = 0x" << hex << this << dec << endl; } private: int m_nData; }; int main() { cout << "main started" << endl; TestClass& c = TestClass(); c.Dump(); c = TestClass(10); c.Dump(); cout << "main ended" << endl; return 0; } // …