std::string VS string 和 error:'string' does not name a type

来源:互联网 发布:js 设置css 编辑:程序博客网 时间:2024/05/01 08:37
std是一个命名空间,命名空间是防止名字冲突的一个策略。string是std命名空间中的一个类,即字符串类。名称空间有助于组织程序中使用标识符,避免名称冲突。由于标准库是使用性的头文件组织实现的,它将名称放在std名称空间中,因此使用这些头文件需要处理名称空间。

程序如下:
程序1:运行正确

#include <iostream>struct Sales_data {    std::string bookNo;    unsigned units_sold = 0;};int main(){    return 0;}

程序2:运行正确

#include <iostream>using namespace std;struct Sales_data {    string bookNo;    unsigned units_sold = 0;};int main(){    return 0;}

程序3:error: ‘string’ does not name a type

#include <iostream>struct Sales_data {    string bookNo;    unsigned units_sold = 0;};int main(){    return 0;}

程序4:error: ‘string’ does not name a type

#include <iostream>struct Sales_data {    string bookNo;    unsigned units_sold = 0;};using namespace std;int main(){    return 0;}

比较:
1.程序1与程序2能实现效果相同,但程序1 using namespace std 导入所有的名称,包括可能并不需要的名称.
对于What requires me to declare “using namespace std;”?
Péter Török给出了这样的解释:
However,using namespace std; is considered a bad practice because you are practically importing the whole standard namespace, thus opening up a lot of possibilities for name clashes. It is better to import only the stuff you are actually using in your code, like using std::string;
2.程序3与程序4发生了同样的错误(’string’ does not name a type),原因归结为未引用命名空间。对于程序4应在struct结构体之前引用。

0 0
原创粉丝点击