[英]Problems passing a 2D array to a method using bracket notation in C++
I have a struct that holds some information about an animation, I want to be able to initialize the struct with a 2D array, without creating and initializing the array first. 我有一个结构,其中包含有关动画的一些信息,我希望能够使用2D数组初始化该结构,而无需先创建和初始化该数组。
The constructor of my Animation struct is as follows: 我的Animation结构的构造函数如下:
Animation( int frames[][2], int count );
I want to achieve something like this: 我想实现以下目标:
Animation* m_PlayerAnimation = new Animation( { { 3, 9 }, { 11, 9 }, { 19, 9 } }, 3 );
I know it's possible as follows, however I'm looking for a 1-line solution: 我知道可能如下,但是我正在寻找一种1行解决方案:
int arr[][2] = { { 3, 9 }, { 11, 9 }, { 19, 9 } };
Animation* m_PlayerAnimation = new Animation( arr, 3 );
Thanks in advance! 提前致谢!
The issue is where you have the argument int frames[][2]
, frames
is a pointer. 问题是您有参数
int frames[][2]
, frames
是一个指针。 So you can't create something in-place there, since it won't be a pointer. 因此,您将无法在其中创建任何东西,因为它不会成为指针。 This is a holdover from C.
这是C的保留。
If you want to be able to in-place create an arbitrary array, you'll have to change your constructor to: 如果想就地创建任意数组,则必须将构造函数更改为:
template <size_t N>
Animation(const int (&frames)[N][2]) { .. }
which lets you write: 它使您可以编写:
Animation a({{0,1}});
At this point the count
argument becomes redundant, as it's replaced by the template parameter N
. 此时,
count
参数变得多余,因为它已由模板参数N
代替。
Alternatively, you could just use vector
: 或者,您可以只使用
vector
:
Animation(std::vector<std::array<int, 2>> const& v) { .. }
which can be used the same way: 可以使用相同的方式:
Animation a({{0, 1}});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.