当我们有两个运算符用于输出对象和这些对象的数组,并尝试输出常量对象数组时,就会涉及到对象运算符。有没有办法强制数组的运算符与常量对象的 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/