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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值