请教:#include 和 using namespace std;的顺序问题
wpx 2003-02-04 06:01:55 请看下面的代码,不必看具体的函数定义部分,
主要看#include 和 using namespace std;的顺序,即main.cpp中的(A)处。
环境是VC6.0,以下是编译正常的程序。
///////// hd.h ////////////////////////////////////////
//声明两个函数
inline const vector<int>* fibon_seq(int size);
inline bool fibon_elem(int pos,int &elem,const std::vector<int>* (*seq_ptr)(int));
///////////////////////////////////////////////////////
/////// function.cpp /////////////////////////////////
//定义两个函数
#include<iostream>
#include<vector>
using namespace std;
const vector<int>* fibon_seq(int size)
{
//......
}
bool fibon_elem(int pos,int &elem,const vector<int>* (*seq_ptr)(int))
{
const vector<int> *pseq=fibon_seq(pos);
elem=(*pseq)[pos-1];
return true;
}
////////////////////////////////////////////////////
////// main.cpp ////////////////////////////////////
//主程序
#include<iostream>
#include<vector>
// 注意!--------------------->(A)
using namespace std;
#include"hd.h"
int main()
{
int elem=0,pos=0;
const vector<int>* (*seq_ptr)(int)=fibon_seq;
cout<<"Input Pos:";
cin >>pos;
if(!fibon_elem(pos,elem,seq_ptr))
cout<<"internal error!";
else
cout<<"is:" << elem;
return 0;
}
/////////////////////////////////////////////////////
在(A)处,如果这里把“#include"hd.h" ”写在"using namespace std;"的前一行,就会编译出类似下面的错误:
d:\test25\hd.h(3) : error C2143: syntax error : missing ';' before '<'
d:\test25\hd.h(3) : error C2433: 'vector' : 'inline' not permitted on data declarations
d:\test25\hd.h(3) : error C2734: 'vector' : const object must be initialized if not extern
d:\test25\hd.h(3) : error C2143: syntax error : missing ';' before '<'
D:\test25\main.cpp(14) : error C2872: 'vector' : ambiguous symbol
D:\test25\main.cpp(14) : error C2143: syntax error : missing ';' before '<'
D:\test25\main.cpp(14) : error C2734: 'vector' : const object must be initialized if not extern
D:\test25\main.cpp(14) : error C2143: syntax error : missing ';' before '<'
D:\test25\main.cpp(16) : error C2065: 'seq_ptr' : undeclared identifier
D:\test25\main.cpp(16) : error C2065: 'fibon_seq' : undeclared identifier
为什么会这样呢?难道 “using namespace std;”必须写在“#include"hd.h" 之前吗?