'string' : undeclared identifier

来源:互联网 发布:淘宝头条能做淘客吗 编辑:程序博客网 时间:2024/05/16 12:43

错误:

#include    <iostream.h>
#include    <string.h>

……

string    st("test    string");  

……

error    C2065:    'string'    :    undeclared    identifier  

解释:

#include    <string>   

using    namespace    std;   

因为在    using    namespace    std;    情况下,

#include    <string>      是使用    C++      string    类库;

#include    <cstring>      是使用    C    的string    操作库函数    ...  

细节 加不加“.h”

#include <iostream.h>

#include <string>

using        namespace       std;

没有错!!

#include <iostream.h>

#include <string.h>

using        namespace       std;

编译有错!!

解释

   “string.h“这个头文件是“旧式c头文件”,而这个文件中没有定义string类(这点应该不奇怪,c语言中哪有什么类啊),这个头文件里面是有关“旧式char-based字符串”的操作函数,注意都是操作char*字符串的“函数”,所以你引用这个头文件,编译器肯定找不到“string”了。   
   “string”这个头文件(没有扩展名)是C++标准化之后的C++头文件,里面才有string类的相关定义(其实,string并不是类,是一个typedef,但是使用的时候不用去管他),而C++标准头文件中的东西都放在namespace    std中了,所以使用的时候要“using    namespace    std”。   
   附:建议楼主不要用"iostream.h",改成“iostream”吧,因为标准已经明确规定不在支持"iostream.h"这种头文件了。

标准写法

#include <iostream>

#include <string>

using        namespace       std;

F: 为什么using    namespace    std;   
        要写在include后面?

Q: 因为include的文件包含名字域std   
如果你把using    namespace    std写在前面,编译器就看不到std这个名字

原创粉丝点击