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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值