【发布时间】:2016-02-26 08:07:46
【问题描述】:
我注意到了
std::string str;
str += 'b'; // works
str.append('b'); // does not work
str.append(1, 'b'); // works, but not as nice as the previous
append 方法不支持添加单个字符有什么原因吗?我假设operator+= 实际上是append 方法的包装器,但事实并非如此。
【问题讨论】:
-
从技术上讲,并不是说它没有那么强大,而是没有人认为有必要写一个
std::string::append(char)。如果你想这样做,请使用+=... -
您可以将
std::string::append(count, char)与count=1或std::string::push_back(char)一起使用 -
滑稽的回答是,没有人能够说服 C++ 标准委员会相信它的必要性。您可以...吗?不过很好的问题。我看不出引入必要的重载会破坏任何东西。
-
@Niall:委员会可能比你想象的要聪明。我不能代表他们说话,但我是这样看的:对于编译器来说,
char只是另一种整数类型。在某些平台上,sizeof( char )和sizeof( int )实际上可能是相同的。查看std::string构造函数和append()重载列表。有一个采用单个整数值的重载可能有点容易出错——而您确实拥有语义相同的std::string( "b" )、append( "b" )、operator+=( "b" )和operator+=( 'b' )。+=只有一个整数重载。