C++:常物件、方法
阿新 • • 發佈:2018-12-31
常物件只能呼叫常方法
#include<iostream> using namespace std; class Test { public: Test(int a, int b):mb(b) { ma = a; //mb = b; } void Show() { cout << "ma:" << ma << endl; cout << "mb:" << mb << endl; } private: int ma; const int mb; }; int main() { const Test test1(10,20);//常物件 test1.Show(); return 0; }
分析:
第一個const修飾的 test1 *this有間接修改的風險,所以編譯器防止發生,直接杜絕掉。
修改:
void Show()const
{
cout << "ma:" << ma << endl;
cout << "mb:" << mb << endl;
}
void Show()const 加const 此時Show是一個常方法
常方法:this型別: const Test* const
相當於 const Test* const this=&test1;
此時 *this被const修飾,沒有被間接修改的風險,編譯器允許通過。
常方法不能呼叫普通方法
void Show()const//常方法 { cout << "ma:" << ma << endl; cout << "mb:" << mb << endl; /**錯誤**/ //Show(ma); //this->Show(ma); // 常方法this指標型別 const Test* const (*this).Show(ma);//左邊是常物件,常物件不能呼叫普通方法 } void Show(int a) { cout << "ma:" << ma << endl; cout << "mb:" << mb << endl; }
//Show(ma);
//this->Show(ma); // 常方法this指標型別 const Test* const
(*this).Show(ma); //左邊是常物件,常物件不能呼叫普通方法
常方法裡面的this指標指向的是常物件,常物件不能呼叫普通方法。
普通物件可以呼叫常方法
int main()
{
Test test2(10,20);
test2.Show();//普通物件可以呼叫常方法
return 0;
}
Test test2(10,20);//普通物件
test2.Show();
這裡相當於:const Test* const this=&test2;
普通方法可以呼叫常方法
void Show()const//常方法
{
cout << "ma:" << ma << endl;
cout << "mb:" << mb << endl;
}
void Show(int a)
{
cout << "ma:" << ma << endl;
cout << "mb:" << mb << endl;
(*this).Show();
}
普通方法裡的this指標指向的是普通物件 ,普通物件可以呼叫常方法。