sách gpt4 ăn đã đi

c++ - 教 cout 优雅地处理空指针

In lại Tác giả: Walker 123 更新时间:2023-11-30 01:45:58 65 4
mua khóa gpt4 giày nike

在我的程序中,我处理有时为 NULL 的 C 风格字符串(类型为 char *)。我想教 cout 优雅地处理这些问题(即打印“(null)”而不是段错误)。

我的第一次尝试:

ostream& operator<< (ostream &out, const char *p_str) {
if (p_str == nullptr)
out << "(null)";
khác
out << p_str;
return out;
}

不起作用,因为它会导致无限递归(在 if 和 else 子句中)。两个问题:

  1. 我可以通过调用原始的 operator<< 来打破无限递归从我重新定义的版本。我该怎么做呢? (这里缺乏 C++ 技能...)
  2. 是否有更好(更惯用)的方式来实现我想要的?

câu trả lời hay nhất

一个快速的解决方案是使用 std::basic_ostream<>::write 改为成员函数

if (p_str == nullptr)
out.write("(null)", 6);
khác
out.write(p_str, std::strlen(p_str)); // need to #include for std::strlen
return out;

关于c++ - 教 cout 优雅地处理空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33762696/

65 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress