標籤:log img 類的變數 ++ put 檔案 turn const public
C++用類來描述對象,類是對現實世界中相似事物的抽象,同是“雙輪車”的>機車和單車,有共同點,也有許多不同點。“車”類是對>機車、單車、汽車等相同點的提取與抽象,如所示。 類的定義分為兩個部分:資料(相當於屬性)和對資料的操作(相當於行為)。 從程式設計的觀點來說,類就是資料類型,是使用者定義的資料類型,對象可以看成某個類的執行個體(某個類的變數)
1 //include "xxxxxx"//自訂標頭檔放在c檔案的前面 2 3 #include <string.h>//c的標頭檔放在c++標頭檔的前面 4 5 #include <iostream> 6 7 8 using std::endl; 9 using std::cout;10 11 class Computer12 {13 public://類為外部提供的提供者14 void print()15 {16 cout << "品牌名:" << _brand << endl;;17 cout << "價格:" << _fprice << endl;18 }19 20 void setBrand(const char * brand)21 {22 strcpy(_brand, brand);23 }24 25 void setPrice(float fprice)26 {27 _fprice = fprice;28 }29 private://只能在類內部進行訪問,體現了類的封裝性30 char _brand[20];//注意代碼風格31 float _fprice;32 33 };34 35 int main()36 {37 int a;38 Computer com;39 com.setBrand("Mac");40 com.setPrice(10000);41 com.print();42 43 system("pause");44 return 0;45 }
c++ 類(1)