静态成员

#include<iostream>
using namespace std;

class A
{
	public:
		A()
		{
			cout<<"A()"<<endl;
			count++;
		}
		~A()
		{
			cout<<"~A()"<<endl;
			count--;
		}

		void out()//非静态成员方法
		{
			cout<<"count:"<<count<<endl;//ok,非静态成员方法可以引用静态成员
			getCount();//ok,非静态成员方法可以引用静态成员方法
		}

		static int getCount() //静态成员方法
		{
			//cout<<x<<endl;//error,静态成员方法不能引用非静态成员
			//out();//error,静态成员方法不能引用非静态成员方法,通过创建对象调用非静态成员方法
			return count;
		}

	private:
		int x;
		static int count;//静态成员变量声明,可以完全脱离对象而存在
};

//静态成员变量必须要初始化,并且要在类外初始化
int A::count; //默认为0

void main()
{	
	//A a1;
	//
	既然创建出了对象实例,count就不可能为0,矛盾 
	//if(a1.getCount() == 0)
	//{
	//
	//}

/*	//只有在count是public情况下使用	
	if(A::count == 0)
	{
		cout<<"count\n";
	}
*/

	if(0 == A::getCount())
	{
		cout << A::getCount << ", " << A::getCount();
	}

}

单例模式

#include<iostream>

using namespace std;

class Sun
{
public:
	//2. 通过公有方法创建出对象,并且通过私有属性curSun保证每次都创建出来的都赋值给同一个对象
	//3. 为了避免矛盾(要创建一个对象,必须通过对象的getSun方法,而调用getSun方法,必须要依赖一个对象),加上static属性就可以脱离对象而存在了
	static Sun *getSun()
	{
		if (NULL == curSun)
			curSun = new Sun();
		return curSun;
	}

private:
	//1.1 构造函数私有化
	Sun()
		:isShining(false)//静态成员变量不能在初始化列表中初始化
	{
		cout << "Sun()" << endl;
	}
	//1.2 拷贝构造函数私有化
	Sun(const Sun &sun)
	{
		cout << "Sun(const Sun &sun)" << endl;
	}
	//1.3 赋值构造函数私有化
	Sun operator=(const Sun &sun)
	{
		cout << "Sun operator=(const Sun &sun)" << endl;
	}

	static bool isShining;
	static Sun *curSun;
};

//静态成员变量必须要初始化
Sun *Sun::curSun = NULL;//默认为NULL
bool Sun::isShining;//默认为false

void main()
{
	//Sun s1,s2,s3;//error	
	Sun::getSun();
	Sun::getSun();
	Sun::getSun();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值