靜態數據和靜態成員函數

#ifndef CHAP_8_H
#define CHAP_8_H
#include "iostream"
using namespace std;
class A
{
private:
 int a;
 static int count;
public:
 static int public_count;
 static void show();
};
int A::count=1;//靜態數據成員的初始化需放在類外執行
int A::public_count=1;

void  A::show()
{
 cout<<"the number is :"<<count<<endl;
 cout<<"the number is :"<<public_count<<endl;
 //cout<<"a is :"<<a<<endl;//靜態成員函數不能訪問非靜態數據成員,除非將對象作爲參數傳入,用對象訪問非靜態數據成員
}
#endif

// chap_8.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "chap_8.h"

int _tmain(int argc, _TCHAR* argv[])
{
 A a;
 //A::count++;//不能訪問靜態私有變量
 A::public_count++;
 A::show();
 return 0;
}

 

發佈了16 篇原創文章 · 獲贊 1 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章