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结构体之前引用。
相关文章推荐
- 由“error string in namespace std does not name a type”错误引发
- ros kinetic版编译error: ‘shared_ptr’ in namespace ‘std’ does not name a template type
- error: ‘shared_ptr’ in namespace ‘std’ does not name a type
- Error: ‘shared_ptr’ in namespace ‘std’ does not name a type
- error: 'function' in namespace 'std' does not name a template type
- ROS Kinetic编译旧版本程序出现 error: ‘shared_ptr’ in namespace ‘std’ does not name a type
- window下用android-ndk-r9d编译.so文件之mutex in namespace 'std' does not name a type
- opencv2.0 源码安装 for x86 make出现error: 'ptrdiff_t' does not name a type 解决
- ’string‘ does not name a type
- error: '[class name]' does not name a type
- ndk 编译webrtc出现 rw_lock_posix.h:35: error: 'pthread_rwlock_t' does not name a type
- 前置声明与C++头文件互相包含导致的error: 'xxx' does not name a type问题
- error: ‘ptrdiff_t’ does not name a type
- error: ‘ptrdiff_t’ does not name a type
- terminating with uncaught exception of type std::logic_error: basic_string::_S_construct NULL not va
- ‘string’ does not name a type 错误解析
- string' does not name a type 及命名空间
- /usr/include/stdlib.h:140:8: error: 'size_t' does not name a type
- ERROR:shared_ptr does not name a type
- 异常:Property 'name' not found on type java.lang.String,attribute items does not accept any