普通成員方法、靜態成員方法、常成員方法的總結
阿新 • • 發佈:2018-12-09
普通的成員方法
- 呼叫的時候必須依賴一個物件
- 可以訪問私有的、保護的成員
- 類的作用域中
static成員方法
- 能訪問部分私有的、保護的成員 eg:靜態成員變數
- 類的作用域中
常成員方法
- 呼叫的時候必須依賴一個物件
- 可以訪問私有的、保護的成員
- 類的作用域中
上程式碼:
// // Created by yanpan on 2018/9/12. // #if 1 #include <iostream> using namespace std; class Counter { public: Counter():_counter(0) { _number++; } void show() //Counter *const this { cout<<"_counter:" <<_counter << endl; } void show()const //const Counter *const this { //不能呼叫普通成員方法 this指向被const修飾 const Counter *const this不能賦值到 Counter *const this cout<<"const _counter: "<<_counter <<endl; } static void shownumber() //呼叫靜態成員方法不需要物件因為靜態成員方法沒有this指標 { cout<<"_nmber: " <<_number << endl; } private: int _counter; static int _number; //靜態成員記憶體在資料段 //這不是定義,是型別的抽象說明 }; int Counter::_number = 0; int main() { Counter *p = new Counter(); p -> show(); delete p; Counter counter1; Counter counter2; Counter counter3; //Counter* const Counter counter4; //const Counter* counter4.show(); // const Counter* 成員方法裡有this指標 this指標指向物件的記憶體 Counter::shownumber(); //靜態的成員函式呼叫不需要一個物件 return 0; } #endif
敲黑板:程式碼裡有註釋和解釋