您的位置:首页 > 其它

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

2016-10-20 16:36 751 查看
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结构体之前引用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string 标准