为类打印输出(打印调试信息)的最佳实践是什么?
what's the best practice to print out(print debugging information) for a class?
我想知道打印类(比如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<<
成为classA
的friend
,例如
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
对象写入cout
、cerr
、clog
、ofstream
、ostringstream
等,还可以写入它们的wchar_t
对应项wcout
、wcerr
、wclog
、wofstream
和wostringstream
。这些在实践中很少使用,但通常实现此功能不会花费您任何费用。诀窍在于std::ostream
和std::wostream
- 所有这些输出流的基类 - 分别是std::basic_ostream<char>
和std::basic_ostream<wchar_t>
的别名。这为我们提供了一种很好的方法来处理两个(以及可能的其他)字符类,而不会重复代码。
某个文件中记录流程的步骤,并在以后查看该文件以查看出了什么问题,则可以选择堵塞。此外,您还可以通过在文件外部记录数据成员来检查数据成员的状态。
- 如何循环打印顶点结构
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 如何在c++中打印目录
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 使用std::source_location报告错误的最佳实践
- 如何将结构插入到集合中并打印集合的成员
- 打印所有儿童树元素的最佳算法?
- 比较文件中的最佳平均成绩并打印学生的姓名
- 在 c++ 中打印到控制台的最佳方式是什么?
- 打印我们在最佳切割后获得的2尺寸杆切割的碎片
- C++-创建虚拟函数以打印调试消息的最佳方式
- 为类打印输出(打印调试信息)的最佳实践是什么?
- 打印 2D 数组矢量的最佳方法是什么