c++打印int类型问题

# include "test.h"

int i = 0;
test :: test(){

}
test :: ~test(){

}
int test::getNumber(){
return i;
}
class test{
public:
int i ;
test();
~test();
int getNumber();
};

// test_2.cpp : Defines the entry point for the console application.

#include <iostream>
#include <string>
#include "test.h"
using namespace std;

int main(int argc, char* argv[])
{

test t;

int s = t.getNumber();

cout << "number is :"<< s << endl;

return 0;
}

各位大侠 这端程序运行完后输出地应该是 0 吧可是为什么输出地是-90922334这样的数字呢我很费解 刚开始研究c++ 问题有些菜哈 大家请赐教~~~

# include "test.h"

int i = 0;//此处的i作用域是全局的

class test{
public:
int i ;//这里重新声明了i,作用域在类test内,getNumber返回的就是此没有赋值的i,去掉此行就返回全局i的值0
test();
~test();
int getNumber();
};
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-12-14
数据溢出了,你的类型又是int型,由于此时最高位刚好为1,因此读成负值。
第2个回答  2010-12-15
最上面的i只是一个全局的变量,而类Test内部的同名变量i是属于类的成员,和外面的i没有任何关系。你建立了类Test的对象t,t中就有一个自己的i值,可是没有被初始化,就会出现很怪的数字。
应该在类的构造函数中初始化i
test::test(){
i = 0;
}
第3个回答  2010-12-14
getNumber()中的i,指的时text类中的i,这个i还没有被初始化,所以为-90922334(当然每个电脑的结果是不同的)。i=0这句对text类没有作用。要想使getNumber得到0的值,需要text中的i在构造函数中初始化。
第4个回答  2010-12-15
最上面的i是个全局的变量,类test中的i是个类的成员,和外面的i没有任何的关系。
每生产一个test类的对象都会有一属于对象自己的i值,所以你生成的对象t就有个自己的i值,但是这个i的值由于没有初始化,就会出现很怪的数字。
应该在构造函数中初始化:
test::test(){
i = 0;
}