一个关于string类赋值问题

fbusybox 2008-06-19 11:25:18
请教一个关于string类赋值问题:

std::string strTemp;

strTemp = std::string(begin_point, end_point);


觉得这种赋值方式乖乖的, 应该是定义一个对象然后赋值给strTemp才比较合法.
因为构造函数没有返回值的,std::string(begin_point, end_point)不像是初始化了一个类的对象,像是调用了构造函数.

欢迎各位Cpluspus牛人指教!

...全文
123 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
fbusybox 2008-06-22
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 handsomezwm 的回复:]


个人认为里面的begin_point ,end_point 应该是两个迭代器;

举个例子来说明:

string s1("nihao,beijing");

string::iterator begin_point=s1.begin(),end_point=s1.end();

string s2(begin_point,end_point);

cout < <s2 < <endl;

结果是:nihao,beijing
[/Quote]

That's right.
fbusybox 2008-06-22
  • 打赏
  • 举报
回复

Renew:

其实这种方式很常见的,特别是在ostream_iterator中常用到,另外当for/while等loop时也需要该种方式.
strTemp = std::string(begin_point, end_point);
实例化某个类,或模板类.

handsomezwm 2008-06-21
  • 打赏
  • 举报
回复


个人认为里面的begin_point ,end_point 应该是两个迭代器;

举个例子来说明:

string s1("nihao,beijing");

string::iterator begin_point=s1.begin(),end_point=s1.end();

string s2(begin_point,end_point);

cout<<s2<<endl;

结果是:nihao,beijing
jieao111 2008-06-20
  • 打赏
  • 举报
回复
是的,你在哪看的代码
晨星 2008-06-20
  • 打赏
  • 举报
回复
为啥不直接这样?
std::string strTemp(begin_point, end_point);
qmm161 2008-06-20
  • 打赏
  • 举报
回复
2楼的写法比较简单吧,如果是你那种写法的话,先调用构造函数创建一个临时对象,然后再赋值
fbusybox 2008-06-20
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 steedhorse 的回复:]
为啥不直接这样?
std::string strTemp(begin_point, end_point);
[/Quote]

有道理...



的确有点多次一举了,不过从中可以学到cplusplus 某方面知识
leehq 2008-06-20
  • 打赏
  • 举报
回复
[Quote=引用楼主 fbusybox 的帖子:]
请教一个关于string类赋值问题:

std::string strTemp;

strTemp = std::string(begin_point, end_point);


觉得这种赋值方式乖乖的, 应该是定义一个对象然后赋值给strTemp才比较合法.
因为构造函数没有返回值的,std::string(begin_point, end_point)不像是初始化了一个类的对象,像是调用了构造函数.

欢迎各位Cpluspus牛人指教!
[/Quote]

的确有点脱裤子放屁的感觉···
HelloDan 2008-06-19
  • 打赏
  • 举报
回复
explicit string ( );
string ( const string& str );
string ( const string& str, size_t pos, size_t n = npos );
string ( const char * s, size_t n );
string ( const char * s );
string ( size_t n, char c );
template<class InputIterator> string (InputIterator begin, InputIterator end);

就是构造一个临时对象来赋值,是正确的。不过也可以是你说的那样。


64,282

社区成员

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

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