c++打印int类型问题

[复制链接]
查看11 | 回复4 | 2010-12-14 23:47:53 | 显示全部楼层 |阅读模式
# 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
#include
#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++ 问题有些菜哈 大家请赐教~~~

回复

使用道具 举报

千问 | 2010-12-14 23:47:53 | 显示全部楼层
# include "test.h"int i = 0;//此处的i作用域是全局的class test{ public:int i ;//这里重新声明了i,作用域在类test内,getNumber返回的就是此没有赋值的i,去掉此行就返回全局i的值0test();~test();int getNumber();};
回复

使用道具 举报

千问 | 2010-12-14 23:47:53 | 显示全部楼层
数据溢出了,你的类型又是int型,由于此时最高位刚好为1,因此读成负值。
回复

使用道具 举报

千问 | 2010-12-14 23:47:53 | 显示全部楼层
最上面的i只是一个全局的变量,而类Test内部的同名变量i是属于类的成员,和外面的i没有任何关系。你建立了类Test的对象t,t中就有一个自己的i值,可是没有被初始化,就会出现很怪的数字。应该在类的构造函数中初始化itest::test(){
i = 0;}
回复

使用道具 举报

千问 | 2010-12-14 23:47:53 | 显示全部楼层
getNumber()中的i,指的时text类中的i,这个i还没有被初始化,所以为-90922334(当然每个电脑的结果是不同的)。i=0这句对text类没有作用。要想使getNumber得到0的值,需要text中的i在构造函数中初始化。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行