这两天在学习的过程中遇到了一些莫名其妙的问题,所有的语言初学者应该都会去写那么无聊无趣的”Hello World!”程序吧,那么来看看我的第一个C++ Hello World:
#include
int main()
{
cout << "Hello World!" << endl;
return 0;
}
保存为test.cpp。
按照我之前的记忆,这个简单的小程序肯定是没问题,我在Cygwin的命令行里面输入:
g++ test.cpp -o test
满以为……呵呵……结果却是
test.cpp: In function `int main()’:
test.cpp:5: error: `cout’ undeclared (first use this function)
test.cpp:5: error: (Each undeclared identifier is reported only once for each function it appears in.)
test.cpp:5: error: `endl’ undeclared (first use this function)
说cout和endl都没有定义!不可能!
我到网上一通乱找,翻来翻去,那些C++的教程全都和我一样,却没有提到我的错误,难道是我错了?是不是我的GCC装得有问题?
没辙了,后来我在gcc的include目录里面打开iostream文件来看才知道,里面使用了std的名字空间!如果上面的程序要想编译通过必须这样写:
#include
using namespace std;
int main()
{
cout << "Hello World!" << endl;
return 0;
}
就没问题了。
我看了一下《C++ Primer》,里面第8章提到了std名字空间,原来标准C++所有的组件全部定义在这个名字空间下,如果要使用标准C++组件,就必须using它,Lippman先生给出的建议是在一个头文件里面统一引用所有要用的组件,这样就不用麻烦每次都写using语句了。
C++的世界已经不像我想象的那样了。
5月 26th, 2006 at 2:03
#include
using namespace std;
6月 29th, 2006 at 17:14
偶然进了这位兄台的blog,,,感觉很好,我也准备学习c++,望交流,我的qq7274465