// 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();