您的位置:首页 > 编程语言 > C语言/C++

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

2013-12-17 10:19 615 查看
参考以下代码。
#include "stdafx.h"
#include <iostream>
#include <string>

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++ 对象 指针
相关文章推荐