static -常見的錯誤 -

static -常見的錯誤

正確的demo1

#include <iostream>

using namespace std;

class Man
{
public:
	Man()
	{
		count++;
	}

	void play() const
	{
		cout<<"I am playing ..."<<endl;
	}

	static int getCount()
	{
		return count;
	}

private:
	static int count; /* 表示總的人數 */

};

int Man::count = 0;

int main(void)
{
	Man man1;
	Man man2;
	cout<<Man::getCount()<<endl;

	system("pause");
	return 0;
}

運行結果:’
在這裏插入圖片描述

錯誤的代碼 demo2

#include <iostream>

using namespace std;

class Man
{
public:
	Man()
	{
		count++;
	}

	void play() const
	{
		cout<<"I am playing ..."<<endl;
	}

	static int getCount()
	{
		/* 類的static方法內, 不能調用這個類的非static方法(實例方法) */
		play(); 

		/* 類的static方法內, 不能訪問非static數據成員(實例數據成員) */
		cout<<age<<endl; 

		return count;
	}

private:
	static int count; /* 表示總的人數 */
	int age; /* 年齡 */
};

int Man::count = 0;

int main(void)
{
	Man man1;
	Man man2;
	cout<<Man::getCount()<<endl;

	system("pause");
	return 0;
}

總結:

類的靜態方法(static 方法) 內, 不能訪問實例方法(非 static 方法)和實例數據成員!

結語:

繼續加油, 量變的積累才能引起質變

時間: 2020-06-21-14-34

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章