C++中如何在函数体(不是main函数)内声明并定义全局对象?

2025-03-02 11:40:32
推荐回答(4个)
回答1:

在VS2010下,修改代码如下:
// C_百度知道_4.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include
using namespace std;

class test {
public:
test() {x = 1;}
int x;
int getX() { return x; }
};

test func() {
test T;
return T;
}

int main() {

cout << func().getX()< return 0;
}
用func()函数返回一个test对象..不知道你是不是要这种效果;呵呵..

回答2:

test Test; //声明Test为全局对象
int main() {
Test = new test(); //初始化全局Test对象
//func(); //这个函数没有任何作用,声明了一个新对象T,没有做其他操作,出了这个函数之后就无效了。另外没有初始化的对象是不能调用的。构造函数貌似也要new test调用吧,你声明Test T的时候不会自动调用构造函数。(我想应该是这样的)
cout << Test.getX();
return 0;
}

回答3:

都说了是全局对象了 当然是在函数体外的声明才行啊 所以在函数体里面是实现不了的
要想获得函数体里面的对象 也就是通过返回值了

回答4:

你想做什么呢?
试试静态函数,静态成员?
#include
using namespace std;
class test {
public:
static int a;
};
int test::a = 10;
void main()
{
cout << test::a << endl;
}
这样的话,就相当于全局变量了。用类名加上与操作符调用a了。