1. 程式人生 > >c++ 類(1)

c++ 類(1)

blog mac main png urn std 操作 ring 對象

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 Computer 12 { 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)