发现一个奇怪的现象,如果C++只声明不初始化会发生什么,你绝对想不到......
#include <iostream>using namespace std;
class Clock
{
public:
void setTime(int newH, int newM, int newS){ hour=newH; minute=newM, second=newS;}
void printTime();
private:
int hour;
int minute;
int second;
};
class Foo
{
private:
int a;
public:
int getA(){return this->a;}
};
void Clock::printTime()
{
printf("%02d:%02d:%02d\n", hour, minute, second);
}
int main(void)
{
/*
Clock clock;
clock.printTime();
*/
int a;
cout << "a = " << a << endl;
/*
Foo b;
cout << "b.getA() = " << b.getA() << endl;
*/
return 0;
} 在main函数内部:
int a; // 声明一个local变量,但是没有初始化
cout << "a = " << a << endl;
这会打印0,不管你信不信,反正C++编译器已经帮你把0补好了!
再写:
int a;
Foo b;
cout << "b.getA() = " << b.getA() << endl;
现在a的值就变成不确定了。 其实本题不需要定义一个类那么麻烦,只填充数据就行了
int a, b, c, d; //多填几个数据
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "d = " << d << endl;
输出:
a = -695388720
b = 32767
c = 0
d = 0
第二次输出
a = -1791576064
b = 32764
c = 0
d = 0
页:
[1]