c++ - const 指针和 const 数组的输出

标签 c++ arrays operators overloading

当我们有两个运算符用于输出对象和这些对象的数组,并尝试输出常量对象数组时,就会涉及到对象运算符。有没有办法强制数组的运算符与常量对象的 c 数组一起使用?

示例代码:

#include <iostream>
#include <cstddef>

using std::size_t;

namespace nm
{
  struct C { int i; };

  template <size_t N>
  using c_c_array = C[N];

  inline std::ostream& operator << (std::ostream& lhs,  C const*) { return lhs << "1\n"; }

  template <size_t N>
  inline std::ostream& operator << (std::ostream& lhs,  c_c_array<N> const&) { return lhs << "2\n"; }

}

int main()
{
  nm::C c{1};

  nm::C arr[5];

  nm::C const c_const{1};

  nm::C const arr_const[5] {{1}, {1}, {1}, {1}, {1}};

  std::cout << &c   // 1 - ok
            << arr  // 2 - ok
            << &c_const   // 1 - ok
            << arr_const; // 1 --ups

  return 0;
}

输出:1 2 1 1

此外,在我的例子中,2 运算符使用 1 作为输出。

最佳答案

根据标准草案N4527 8.5/p7.3 初始化器 [dcl.init](强调我的):

  • Otherwise, no initialization is performed.

If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

因此,您必须为 class C 定义默认构造函数才能解决此问题。

关于c++ - const 指针和 const 数组的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33239935/

相关文章:

c++ - C++ 中的抛出和三元运算符

c 中的 char 数组 end char

c、如何阅读算子问题,基础知识

c++ - 从 main 访问类的 protected 成员

c++ - MSVC 对这段代码很满意,但 GCC 不太热衷

ios - Swift 2 结构与数组

python - 使用字典来索引并行数组?

C++通用模板化类算术

c++ - 旧代码中的神秘行 "??!??!"

c++ - 是否可以将 CRTP 与本身模板化的派生类一起使用?