方法一:
test.hpp
class staticTest
{
public:
staticTest(){testValue = 1;}
~staticTest(){}
static staticTest * getInstance(){return &_instance;}
void printValue();
public:
int testValue;
static staticTest _instance; //静态类对象成员
};
---------------------------------------------------------------------------
test.cpp
staticTest staticTest::_instance; //声明静态全局变量,
同时为静态类对象分配了存储空间//静态全局变变量的作用域为文件
void staticTest::printValue()
{
testValue++;
printf("staticTest::print value: %d \n", testValue);
return;
}
int main()
{
staticTest *ps1 = NULL;
staticTest *ps2 = NULL;
staticTest *ps3 = NULL;
printf("static test 0 addr: %X \n", &staticTest::_instance); //此处,已经为静态类对象分配了存储空间,地址为49C788
ps1 = staticTest::getInstance(); //获取静态对象
printf("static test 1 addr: %X \n", ps1); //静态对象地址,地址为49C788
printf("static test 1 value: %d \n", ps1->testValue); //第一次访问静态类对象,testValue: 1
ps1->printValue(); //静态类对象的数据成员加1,testValue++ --> testValue: 2
ps2 = staticTest::getInstance(); //获取静态对象
printf("static test 2 addr: %X \n", ps2); //静态对象地址,地址为49C788
printf("static test 2 value: %d \n", ps2->testValue); //静态对象数据成员的值已经改变,testValue : 2
ps2->printValue(); //testValue++ --> testValue: 3
ps3 = new staticTest(); //创建普通staticTest类对象
printf("static test 3 addr: %X \n", ps3); //普通类对象地址为5D15E8
printf("static test 3 value: %d \n", ps3->testValue); //普通类对象的数据成员,testValue: 1
ps3->printValue(); //testValue++ --> testValue: 2
getchar();
return 0;
}
VS2005运行结果:
方法二:
test.hpp
class test
{
public:
test(){testValue = 1;}
~test(){}
static test * getInstance();
void printValue();
public:
int testValue;
};
-------------------------------------------------------------------------------
test.cpp
test * test::getInstance()
{
static test s_test;
return &s_test;
}
void test::printValue()
{
testValue++;
printf("test::print value: %d \n", testValue);
return;
}
int main()
{
test *p1 = NULL;
test *p2 = NULL;
test *p3 = NULL;
p1 = test::getInstance(); //第一次调用getInstance()时创建了静态对象(static test s_test;)
printf("test 1 addr: %X \n", p1); //静态类对象地址49C780
printf("test 1 value: %d \n", test::getInstance()->testValue);
p1->printValue(); //testValue++
p2 = test::getInstance(); //静态类对象地址49C780
printf("test 2 addr: %X \n", p2);
printf("test 2 value: %d \n", test::getInstance()->testValue);
p2->printValue(); //testValue++
p3 = new test(); //创建普通类test对象
printf("test 3 addr: %X \n", p3); //普通对象地址为5D15A8
printf("test 3 value: %d \n", p3->testValue); //testValue: 1
p3->printValue(); //testValue++
getchar();
return 0;
}
VS2005运行结果: