【发布时间】:2018-07-20 05:41:30
【问题描述】:
我创建了一个继承 std::array 的自定义数组。 但它不能使用 std::array 的相同语句初始化。 谁能告诉我为什么这不起作用并帮助我正确修改我的代码?
这里是编译错误信息:
main.cpp: In function 'int main()':
main.cpp:32:35: error: no matching function for call to 'my_array::my_array()'
my_array<int, 2> b { {1, 2} }; // compile error
^
main.cpp:13:8: note: candidate: my_array::my_array()
struct my_array : std::array<T,N>
^
main.cpp:13:8: note: candidate expects 0 arguments, 1 provided
main.cpp:13:8: note: candidate: constexpr my_array::my_array(const my_array&)
main.cpp:13:8: note: no known conversion for argument 1 from '' to 'const my_array&'
main.cpp:13:8: note: candidate: constexpr my_array::my_array(my_array&&)
main.cpp:13:8: note: no known conversion for argument 1 from '' to 'my_array&&'
下面是我的实现代码。 提前致谢。
#include<iostream>
#include<array>
template<typename T, std::size_t N>
struct my_array : std::array<T,N>
{
T& operator[](std::size_t n)
{
if(!(n < N))
std::cout << "out of range" << std::endl;
return (*static_cast<std::array<T,N>*>(this))[n];
}
const T& operator[](std::size_t n) const
{
if(!(n < N))
std::cout << "out of range" << std::endl;
return (*static_cast<const std::array<T,N>*>(this))[n];
}
};
int main(void)
{
std::array<int, 2> a { {1, 2} }; // no error
my_array<int, 2> b { {1, 2} }; // compile error
}
【问题讨论】:
-
与您的问题无关,但
operator[]函数没有边界检查是有原因的。如果您想要边界检查,请改用at。 -
if(n > N) it is out of bound 看起来你在做相反的事情。
-
很确定你已经违反了在 C++17 之前的编译器中使用基类聚合初始化的规则。试图找到确切的裁决。没有太多机会使用 C++17。
-
通常,如果有人询问编译错误,必须将它们包含在问题中(通常,它们会准确说明问题所在)。
标签: c++ arrays initialization std