C++ --> 類(Classes)

來源:互聯網
上載者:User

標籤:

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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.