C++PrimerPlus學習之物件和類
阿新 • • 發佈:2018-11-03
OOP的特性
- 抽象
- 封裝和資料隱藏
- 多型
- 繼承
- 程式碼的可重用性
類
-
將抽象轉換為使用者定義型別的C++工具
-
資料表示+操縱資料的方法
-
一個例子
//stock00.h #ifndef STOCK00_H_INCLUDED #define STOCK00_H_INCLUDED #include<string> class Stock//常見寫法,將首字母大寫 { private: //1,私有成員只能被公有成員使用。2,這個可省略,class預設訪問型別為private,而struct預設訪問型別為public。
//stock.cpp #include<iostream> #include"stock00.h" Stock::Stock() {} Stock::Stock(const std::
//main.cpp #include<iostream> #include"stock00.h" using namespace std; int main() { Stock gs=Stock("gs",12,20.0); gs.show(); cout<<gs.getcompany()<<endl; } /* output company: gs shares: 12 share_val: 20 tot_val: 240 gs good bye gs */
-
一個小點
接受一個引數的建構函式允許使用賦值語法將物件初始化為一個值Object obj = 1; // 如果有建構函式 Object(int)的話
this指標
-
this指標指向用來呼叫成員函式的物件
-
this指標被作為隱藏參傳遞給成員函式 – 且只能是第一個引數
-
在成員函式後面加const的實質是給第一個引數即this指標加const屬性
//stock00.h const Stock &topval(const Stock &s)const; //stock00.cpp const Stock &Stock::topval(const Stock &s)const { if(s.total_val>total_val)return s; return *this; }
類作用域
-
作用域為類的常量
//列舉型別 class Bakery { private: enum {Months=12}; double costs[Months]; ... } //使用關鍵字static class Bakery { private: static const int Months=12; double costs[Months]; } //Months為靜態變數,它和其他靜態變數儲存在一起。
-
作用域內列舉(C++11)
- 常規列舉可自動轉換為整型,但作用域內列舉不能隱式地轉換為整型。
- 可以顯式地指出底層整型型別。
#include<bits/stdc++.h> using namespace std; /* 預設情況下,列舉的底層型別為int */ //作用域內列舉 enum class egg{Small,Medium,Large,Jumbo}; enum class t_shirt{Small,Medium,Large,Xlarge};//這樣就不會發生衝突了 //常規列舉 enum egg_old{Small,Medium,Large,Jumbo}; //可以顯式的指出列舉的底層型別 enum class : short pizza{Small,Medium,Large,XLarge}; int main() { egg choice=egg::Large; t_shirt Floyd=t_shirt::Large; egg_old one=Medium; int king=one;// allowed //int ring=choice;//not allowed if(king<Jumbo) //allowed cout<<"hello world"<<endl; if(king<t_shirt::Large)//not allowed cout<<"cool boy"<<endl; //顯示轉換 int Frodo=int(t_shirt::Small); }