源程序:
//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");
}
運行結果: