定義一個Dog類,它和靜態數據成員Dogs記錄Dog的個體數目。靜態成員函數GetDogs用來存取Dogs。設計並測試這個類--簡單


源程序:

//4.定義一個 Dog 類,它用靜態數據成員 Dogs 記錄 Dog 的個體數目,靜態成員函數 GetDogs

//用來存取 Dogs。設計並測試這個類。

#include < iostream >

using namespace std;

class Dog

{

private:

  static int dogs;//靜態數據成員,記錄 Dog 的個體數目

public:

  Dog() {}

  void setDogs(int a)

  {

    dogs = a;

  }

  static int getDogs()//靜態成員函數用來存取dogs

  {

    return dogs;

  }

};

int Dog::dogs = 25;//初始化靜態數據成員

void main()

{

  cout << "未定義 Dog 類對象之前:x = " << Dog::getDogs() << endl;; //x 在產生對象之前即存在,輸出 25

  Dog a, b;

  cout << "a 中 x:" << a.getDogs() << endl;

  cout << "b 中 x:" << b.getDogs() << endl;

  a.setDogs(360);

  cout << "給對象 a 中的 x 設置值后:" << endl;//360傳給a,a賦值給dogs;dogs是靜態變量,對所有的對象共享

  cout << "a 中 x:" << a.getDogs() << endl;

  cout << "b 中 x:" << b.getDogs() << endl;//所以,輸入全都為360

 

  system("pause");

}

 運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM