重载 operator<< 数组而不需要 class

Overloading operator<< for array without the need of a class

我有一个问题。在 C++ 中,我可以重载 operator<<,这样我就可以打印给定大小的数组,而不需要 class 吗? 我设法打印了一个数组,但前提是我使该数组成为 class.

的成员

是的,你绝对可以做到。

只需继续定义该运算符的重载即可获取您想要的任何内容。它不需要是 class 类型。

所以,像这样:

template <typename T, std::size_t N>
std::ostream& operator<<(std::ostream& os, const T (&arr)[N])
{
   for (const auto& el : arr)
      os << el << ' ';

   return os;
}

(live demo)

但是,我告诫不要过火;使用您的代码的其他程序员可能不会期望它,并且没有很多其他 non-class 类型没有像这样的重载(考虑所有整数,char 类型,bool 并且流式传输时指针已经 "do something")。


完整的演示代码,供后代使用:

#include <iostream>
#include <cstddef>

template <typename T, std::size_t N>
std::ostream& operator<<(std::ostream& os, const T (&arr)[N])
{
   for (const auto& el : arr)
      os << el << ' ';

   return os;
}

int main()
{
    int array[] = {6,2,8,9,2};
    std::cout << array << '\n';
}

// Output: 6 2 8 9 2

另一种方法是使用 std::copystd::ostream_iterator

#include <iostream>
#include <algorithm>
#include <iterator>
#include <cstddef>

template <typename T, auto N>
auto& operator<<(std::ostream& os, T(&arr)[N])
{
  std::copy(std::cbegin(arr), std::cend(arr), std::ostream_iterator<T>(os, " "));
  return os;
}

int main()
{
    int array[] = { 6, 2, 8, 9, 2};
    std::cout << array << '\n';
}

// Output: 6 2 8 9 2