(1)C++ iostream和iostream.h的区别
#include <iostream.h>非标准输入输出流
#include <iostream>标准输入输出流
C++中为了避免名字定义冲突,特别引入了“名字空间的定义”,即namespace。当代码中用<iostream.h>时,输出可直接引用cout<<x;因为<iostream.h>继承C语言的标准库文件,未引入名字空间定义,所以可直接使用。
当代码中引入<iostream>时,输出需要引用std::cout<<x;如果还是按原来的方法就会有错。所以使用<iostream>时,引入std::有以下方法:
1,using namespace std;
cout<<x;
2,using std::cout;
cout<<x;
3,最基本的std::cout<<x;
这回你该知道为什么通常用#include <iostream>时,要用using namespace std;了吧。如果你不用这个,就要在使用cout时,用后两种方法了。其他头文件也是同样的道理。(补充:有“.h”的就是非标准的C的标准库函数,无“.h”的,就要用到命令空间,是C++的。)
(2)关于namespace
NameSpace:名字空间,之所以出来这样一个东西,是因为人类可用的单词数太少,并且不同的人写的程序不可能所有的变量都没有重名现象,对于库来说这个问题尤其严重。如果两个人写的库文件中出现同名的变量或函数(不可避免),使用起来就有问题了。为了解决这个问题,引入了名字空间这个概念,通过使用 namespace xxx;你所使用的库函数或变量就是在该名字空间中定义的,这样一来就不会引起不必要的冲突了。
实例:
#include "stdafx.h"
#include <iostream> //使用C++头文件
using namespace std; //使用std命名空间
namespace savitch1
{
void greeting() //在savitch1空间内定义的greeting函数
{
cout<<"hello from namespace savitch1.\n";
}
}
namespace savitch2 //在savitch2空间内定义的greeting函数
{
void greeting()
{
cout <<"Greeting from namespace savitch2.\n";
}
}
void big_greeting()
{
cout<<"a big global hello.\n"; //直接使用std的函数
}
int main(int argc, char* argv[])
{
{
using namespace savitch2;
greeting(); //执行空间savitch2的greeting函数
}
{
using namespace savitch1;
greeting(); //执行空间savitch1的greeting函数
}
big_greeting();
return 0;
}
运行结果是:
Greeting from namespace savitch2.
hello from namespace savitch1.
a big global hello.
Press any key to continue
如上,这样就避免了同名函数的使用错误