gpt4 book ai didi

c++ - 为什么字符串类没有预定义的 << 运算符 (operator<<) 以便字符串像 ostringstreams 一样工作?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:46:35 24 4
gpt4 key购买 nike

在我看来,定义 << 运算符 (operator<<) 以直接使用字符串比必须使用 ostringstreams 然后再转换回字符串更优雅。为什么 C++ 不能开箱即用?

#include <string>
#include <sstream>
#include <iostream>
using namespace std;

template <class T>
string& operator<<(string& s, T a) {
ostringstream ss;
ss << a;
s.append(ss.str());
return s;
}
int main() {
string s;
// this prints out: "inserting text and a number(1)"
cout << (s << "inserting text and a number (" << 1 << ")\n");

// normal way
ostringstream os;
os << "inserting text and a number(" << 1 << ")\n";
cout << os.str();
}

最佳答案

流包含额外的状态。想象一下,如果这是可能的:

std::string str;
int n = 1234;
str << std::hex;
str << n;
return str; // returns "0x4d2" (or something, I forget)

为了维持这个额外的状态,字符串必须有这个状态的存储空间。 C++ 标准委员会(和一般的 C++ 程序员)通常不赞成过多的资源消耗,其座右铭是“只为使用的东西付费”。因此,字符串类中没有额外的字段。

主观答案: 是我认为 std::string 类一开始就设计得很糟糕,尤其是与 C++ 出色的标准库的其他部分相比,向 std::string 添加功能只会让事情变得更糟。这是一个非常主观的意见,请随意将我视为狂热的疯子。

关于c++ - 为什么字符串类没有预定义的 << 运算符 (operator<<) 以便字符串像 ostringstreams 一样工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14795481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com