【C++學習教程03】面向物件程式設計的基本知識&行內函數
阿新 • • 發佈:2021-01-02
目錄
參考資料
- 範磊C++(第6課)
- Xcode & VS2015
面向物件的概念
- 抽象
- 封裝
- 繼承
- 多型
行內函數
參考: 菜鳥驛站.
- 這其實就是個空間代價換時間的i節省。所以行內函數一般都是1-5行的小函式。
- 類結構中所在的類說明內部定義的函式是行內函數。
程式碼
#include "stdafx.h" #include <stdlib.h> #include <iostream> using namespace std; class human //僅僅是宣告不佔記憶體 { public: void GetStature() { cout << "stature:"<<stature<<endl; }//駱駝命名法 void get_Weight();//下劃線命名法 void SetStature(int x) { stature = x; } //宣告和定義不建議放在一起 //放在一起就是“行內函數”會增加程式的空間 void SetWeight(int x); private://類的成員預設私有,建議使用介面函式來訪問 int stature; int weight; }; //行內函數 inline int print(); int print(){return 1; } void human::get_Weight() { cout << "weight:"<<weight << endl; } void human::SetWeight(int x) { if (x > 0 && x < 100) weight = x; else cout << "error" << endl; } int main(int argc, const char * argv[]) { // insert code here... human Mike; Mike.SetStature(178); Mike.SetWeight(67); Mike.GetStature(); Mike.get_Weight(); cout << print(); system("pause"); return 0; }
總結
資料成員都儲存在private,然後通過介面來訪問。