C++ 使用 toString() 方法有什么问题

标签 c++ string operator-overloading iostream cout

我刚刚遇到 this question这是关于如何能够通过

std::cout << x << std::endl;

据我了解,实现此目的的标准方法是重载 ostreams << 运算符。但是,这是向 ostream 而不是我的类(class)添加了一个功能。

备选方案(也作为上述问题的答案给出)是覆盖字符串转换运算符。然而,这伴随着导致“意外转换和难以追踪的错误”的警告。

现在我想知道编写一个 toString() 方法然后通过它使用它是否有任何缺点

std::cout << x.toString() << std::endl;

最佳答案

输出流处理输出格式和输出。所以你的toString()方法客户端将无法像管理其他所有内容一样管理对象的格式:

// set specific formatting options for printing a value
std::cout << std::scientific << std::setprecision(10) << 10.0 << '\n'; // prints 1.0000000000e+01

// set formatting based on user's cultural conventions
std::cout.imbue(std::locale(""));
std::cout << 10000000 << '\n'; // depending on your system configuration may print "10,000,000"

也许您不关心允许任何格式,所以这可能无关紧要。

另一个考虑因素是,输出到一个流并不需要整个字符串表示立即在内存中,但是您的 toString()方法确实如此。


其他人已经指出了这一点,但我认为更清晰的说法是您的类接口(interface)不仅限于它提供的方法,还包括您围绕它构建的其他函数,包括非成员函数,例如作为 operator<<你提供的重载。即使它不是您类的方法,您仍应将其视为类接口(interface)的一部分。

这是一篇讨论此问题的文章,也许您会发现它有帮助:How Non-Member Functions Improve Encapsulation


这是一个重载 operator<< 的简单示例对于用户定义的类:

#include <iostream>

struct MyClass {
  int n;
};

std::ostream &operator<< (std::ostream &os, MyClass const &m) {
  for (int i = 0; i < m.n; ++i) {
    os << i << ' ';
  }
  return os;
}

int main() {
  MyClass c = {1000000};
  std::cout << c << '\n';
}

关于C++ 使用 toString() 方法有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27269423/

相关文章:

javascript - CodeWars/合并字符串检查器

输入对象没有 const 的 C++ 重载 << 会产生错误,该错误随 const 对象一起消失

使用模板的 C++ 重载输出运算符

C++ 运算符用指针重载

c++ - 试图减少几乎但不完全是整数类的速度开销

C++ : memory management

c++ - 为什么 const x 在 multi include 时没问题

c - 如何在字符串前添加减号? (在 C 中)

c++ - 使用 : Construction of objects at predetermined location in C++

c - C 中的反转字符串函数