c++中不包含string头文件和包含string头文件的区别何在,为何都能使用string

一苇渡江694
博客专家认证
2015-12-11 09:22:35
不包含<string>
可以这样写:
string csdn_str = "wo shi shei";
cout << str << endl;//错误
cout<<str.c_str()<<endl;//正确

但是包含了<string>t头文件
就可以
cout<<str<<endl;//正确
...全文
901 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
paschen 版主 2015-12-12
  • 打赏
  • 举报
回复
string可能包含在多个文件里,没包含也可能用可能你间接包含了其部分方法 cout << str << endl; 这句需要有对string的<<重载运算符(按你描述应该该重载函数是写在了<string>里) cout<<str.c_str()<<endl; 这句已经将string转成了char*了,所以只需要c_str()成员函数即可(可能你已经间接包含了)
fefe82 2015-12-12
  • 打赏
  • 举报
回复
在 VS2015 , <iostream> 包含了 <string> 的大部分内容。
一苇渡江694 2015-12-11
  • 打赏
  • 举报
回复
引用 2 楼 wangshubo1989 的回复:
[quote=引用 楼主 wangshubo1989 的回复:] 不包含<string> 可以这样写: string csdn_str = "wo shi shei"; cout << str << endl;//错误 cout<<str.c_str()<<endl;//正确 但是包含了<string>t头文件 就可以 cout<<str<<endl;//正确
那为什么没有包含头文件 就可以使用string 定义变量呢?[/quote] #include <iostream> #include <algorithm> //#include<string> using namespace std; int main() { string str = "heLLo"; transform(str.begin(), str.end(), str.begin(), toupper); //cout << str << endl; cout << str.c_str() << endl; transform(str.begin(), str.end(), str.begin(), tolower); cout << str.c_str() << endl; cout << str.c_str() << endl; return 0; }
一苇渡江694 2015-12-11
  • 打赏
  • 举报
回复
引用 3 楼 fefe82 的回复:
某些其它的头可能包含了 <string>
#include <iostream> #include <algorithm> //#include<string> using namespace std; int main() { string str = "heLLo"; transform(str.begin(), str.end(), str.begin(), toupper); //cout << str << endl; cout << str.c_str() << endl; transform(str.begin(), str.end(), str.begin(), tolower); cout << str.c_str() << endl; cout << str.c_str() << endl; return 0; }
D41D8CD98F 2015-12-11
  • 打赏
  • 举报
回复
N4567 § 17.6.2.2[using.headers]p3 A translation unit shall include a header only outside of any declaration or definition, and shall include the header lexically before the first reference in that translation unit to any of the entities declared in that header. No diagnostic is required. string 类型是在 <string> 头文件里声明的,如果在使用 string 类型前没有包含 <string> 头文件,就是 No diagnostic is required No diagnostic is required,完整说法应该是 ill-formed no diagnostic required。 跟 Undefined behavior 类似, ill-formed no diagnostic required 也有“后果不可预料”这样的意思
fefe82 2015-12-11
  • 打赏
  • 举报
回复
某些其它的头可能包含了 <string>
一苇渡江694 2015-12-11
  • 打赏
  • 举报
回复
引用 楼主 wangshubo1989 的回复:
不包含<string> 可以这样写: string csdn_str = "wo shi shei"; cout << str << endl;//错误 cout<<str.c_str()<<endl;//正确 但是包含了<string>t头文件 就可以 cout<<str<<endl;//正确
那为什么没有包含头文件 就可以使用string 定义变量呢?
fefe82 2015-12-11
  • 打赏
  • 举报
回复
给完整程序。 string 提供了 std::basic_string, std::char_traiits ... 等模板

64,653

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧