static 數據成員和函數成員

#include<iostream>
#include<string>

using namespace std;

class base
{
private:
	int a,b;
	string name;
public:
	base(string name = " "):a(10),b(10){}  // 靜態成員變量不能在初始化列表中初始化
	static int c;   //聲明靜態數據成員
	// const static int m = 0;  報錯,VC++ 不支持這種用法,但dev支持
    static int fun() //  static 只能訪問static 數據成員變量,因爲不會傳遞this指針,所以不能訪問一般數據變量和非static成員函數,所以只能返回數據成員c 
	{
	  return c;
	}

	static int foo();
};

 int base::foo()  //在類外部定義static 函數時不用加static關鍵字
{
  return c;
}

//static int base::c = 10;  報錯說只能用在member function 
int base::c = 10; //   right

int main()
{
  
  
  
  return 0;
}

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