標籤:
1.類的定義:C++中使用關鍵字 class 來定義類, 其基本形式如下:
1 class 類名2 {3 public:4 //公用的行為或屬性5 6 private:7 //公用的行為或屬性8 };View Code
說明:
①. 類名 需要遵循一般的命名規則;
②. public 與 private 為屬性/方法限制的關鍵字, private 表示該部分內容是私密的, 不能被外部所訪問或調用, 只能被本類內部訪問; 而 public 表示公開的屬性和方法, 外界可以直接存取或者調用。
一般來說類的屬性成員都應設定為private, public只留給那些被外界用來調用的函數介面, 但這並非是強制規定, 可以根據需要進行調整;
③. 結束部分的分號不能省略。
例:
#include <iostream>using namespace std; class Point{ public : void SetPoint(int x , int y) { xPost = x; yPost = y; } void PrintPoint() { cout <<"============================================" << endl; cout << " x = " << xPost << endl; cout << " y = " << yPost << endl; } private : int xPost; int yPost;};int main() { cout <<"============================================" << endl; Point M; //用定義好的類建立一個對象 點M M.SetPoint(10, 20); //設定 M點 的x,y值 M.PrintPoint(); //輸出 M點 的資訊 cout <<"============================================" << endl; while(1) { } return 0;}View Code
#include <iostream>using namespace std; class Point{ public : void SetPoint(int x , int y); void PrintPoint(); private : int xPost; int yPost;};void Point::SetPoint(int x , int y){ xPost = x; yPost = y;}void Point::PrintPoint(){ cout <<"============================================" << endl; cout << " x = " << xPost << endl; cout << " y = " << yPost << endl;}int main() { cout <<"============================================" << endl; Point M; //用定義好的類建立一個對象 點M M.SetPoint(10, 20); //設定 M點 的x,y值 M.PrintPoint(); //輸出 M點 的資訊 cout <<"============================================" << endl; while(1) { } return 0;}View Code
C++ --> 類(Classes)