类中的静态类成员变量

// MyObj.h
#pragma once
#include <iostream>
using namespace std;

class CMyObj
{
public:
	CMyObj()
	{
		cout << "[CMyObj::CMyObj()]" << endl;
	}

	~CMyObj()
	{
		cout << "CMyObj::~CMyObj()" << endl;
	}

};
// Account.h
#ifndef ACCOUNT_H
#define ACCOUNT_H

#include <string>
class CMyObj;

class Account 
{
public:
	Account() : amount(0.0) { }
	Account(const std::string &s, double amt) :
		owner(s), amount(amt) { }

public:
	static void releaseMyObj();

private:
	std::string owner;
	double amount = 0.0;

	static CMyObj* m_pStaticMyObj;
	static CMyObj* initMyObj();
};

#endif
// Account.cpp
#include "Account.h"
#include "MyObj.h"
#include <iostream>
#include <string>
using namespace std;

CMyObj* Account::m_pStaticMyObj = initMyObj();

CMyObj* Account::initMyObj()
{
	cout << "[Account::initMyObj()]" << endl;

	return new CMyObj();
}

void Account::releaseMyObj()
{
	if (m_pStaticMyObj != NULL)
	{
		delete m_pStaticMyObj;
		m_pStaticMyObj = NULL;
	}
}
// StaticObjectDemo.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "Account.h"
#include <iostream>
// Namespace for using cout.
using namespace std;

/* 静态类成员变量演示 */
int _tmain(int argc, _TCHAR* argv[])
{
	cout << __FUNCSIG__ << endl;
	Account::releaseMyObj();

	return 0;
}

编译环境:Microsoft Visual C++ 2013

程序输出:

[Account::initMyObj()]
[CMyObj::CMyObj()]
int __cdecl wmain(int,wchar_t *[])
CMyObj::~CMyObj()

分析说明:C++类中,对于静态类成员变量,会在定义静态类成员变量时生成对象(如果会生成对象的话),对于本例,在下面的语句中,生成了对象。

// Account.cpp
CMyObj* Account::m_pStaticMyObj = initMyObj();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值