C++ 引用型別const形參的用法
阿新 • • 發佈:2019-02-07
今天在看《C++沉思錄》後,對const引用形參的用法又有了進一步的認識。在此,想把我個人對const引用形參的了
解分享給大家。如果有不到之處,還往各位同仁指出。
第一種情況:
class TestB{
public :
int b;
TestB(){ b = 0; };
};
void func(const TestB &tt)
{
++tt.b; //會提示錯誤,表示式必須是可修改的左值
}
就是說我們無法在函式體內修改 const引用形參的值。
第二種情況:
class TestA{ public: int a; TestA(int a) :a(a){}; TestA(){ a = 0;} }; class TestB{ public : TestA *test; TestB(){ test = new TestA(5); }; }; void func(const TestB &tt) { ++tt.test->a; //在TestB型別中,修改TestA指標物件在堆記憶體上儲存的值是可以的。 printf("%d\n", tt.test->a); } int _tmain(int argc, _TCHAR* argv[]) { TestB t1; func(t1); system("pause"); return 0; }
第三種情況:
class TestA
{
public:
int a;
TestA(int a) :a(a){};
TestA(){ a = 0; }
};
class TestB{
public :
TestA *test;
int b;
TestB(){ test = new TestA(5); b=0; };
};
void func(const TestB &tt)
{
TestA *tt1 = new TestA(2);
tt.test = tt1; //同樣會提示錯誤,表示式必須是可修改的左值
}
由此看來,const引用形參中如果包含了其他非const自定義物件指標時,是可以修改它指向物件的值的,但是不能夠變更它指向物件的記憶體地址。