c++ 带参数构造全局变量实现方法

参考以下代码。

#include "stdafx.h"
#include 
#include 

class Test
{
public:
	int a;
	int b;

	Test();
	Test(int c);  // 带参数构造函数
 	~Test();
};


Test::Test(int c)
{
	a = c;
}

Test * createTestObject()
{
	Test *tmp = new Test(2);
	return tmp;
}

Test * testmain; // 全局变量的定义
int _tmain(int argc, _TCHAR* argv[])
{
	testmain = createTestObject();
	std::cout << "get the result: " << testmain->a << std::endl;
	system("PAUSE");
	return 0;
}

实现方法介绍:

1.定义一个全局的指针,通过指针来访问全局的对象。

2.实现一个create的函数创建对象,当然也要实现一个销毁对象的方法。

3.也可以在class中实现一个static的接口,通过该接口创建对象。


 

你可能感兴趣的:(c/c++)