为类打印输出(打印调试信息)的最佳实践是什么?

what's the best practice to print out(print debugging information) for a class?

本文关键字:打印 最佳 是什么 信息 输出 调试      更新时间:2023-10-16

我想知道打印类(比如classA)的最佳实践是什么,我有几种方法

A类;

1)定义一个调试方法,并在该方法中,打印出它的所有成员。

2)定义一个str()方法,并使用cout<<ca.str()

3)定义类似字符串转换的东西(我还不确定如何),然后只使用cout<<ca

通常的方法是重载operator<<大致如下:

std::ostream &operator<<(std::ostream &out, classA const &a) {
  // precise formatting depends on your use case. Do the same thing you would
  // if you wanted to print a to cout or a file, because that is what this code
  // will end up doing.
  out << a.some_data() << ", " << a.some_more_data();
  return out;
}

如果classA具有有限的接口(不公开所有相关的数据成员),则可能需要使operator<<成为classAfriend,例如

class A {
public:
  // stuff
  friend operator<<(std::ostream &out, classA const &a);
};
// private members can then be accessed
std::ostream &operator<<(std::ostream &out, classA const &a) {
  out << a.some_private_member << ", " << a.some_other_private_member;
  return out;
}

通常没有充分的理由阻止对私有成员的读取访问,然后允许用户按operator<<转储,因为它将是相当泄漏的访问控制。

然后,这使您能够编写

classA a;
std::cout << a;
std::ofstream file("foo.txt");
file << a;
std::ostringstream fmt;
fmt << a;
std::string s = fmt.str();

等等。

作为样式说明:可以写

std::ostream &operator<<(std::ostream &out, classA const &a) {
  // precise formatting depends on your use case
  return out << a.some_data() << ", " << a.some_more_data();
}

这实现了与拆分返回相同的目标,因为operator<<(按照惯例)返回传递到其中的相同流对象(以启用<<的链接,如 std::cout << i << j << k; )。

风格说明 2:如果classA中没有任何困难,则升级此技术是编写

template<typename char_type>
std::basic_ostream<char_type> &operator<<(std::basic_ostream<char_type> &out, classA const &a) {
  // rest as before. Put it in a header because it is a function template now.
}

这样,您不仅可以将classA对象写入coutcerrclogofstreamostringstream等,还可以写入它们的wchar_t对应项wcoutwcerrwclogwofstreamwostringstream。这些在实践中很少使用,但通常实现此功能不会花费您任何费用。诀窍在于std::ostreamstd::wostream - 所有这些输出流的基类 - 分别是std::basic_ostream<char>std::basic_ostream<wchar_t>的别名。这为我们提供了一种很好的方法来处理两个(以及可能的其他)字符类,而不会重复代码。

如果您想在

某个文件中记录流程的步骤,并在以后查看该文件以查看出了什么问题,则可以选择堵塞。此外,您还可以通过在文件外部记录数据成员来检查数据成员的状态。