我正在尝试拥有一个带有派生类应设置的数组的基类。该应用程序是一个俄罗斯方块游戏,因此我想拥有一个baseshape类,该类别具有每个派生类(即Squareshape,tshape等)的旋转阵列,将根据特定形状的旋转设置。
。class BaseShape
{
public:
BaseShape();
BaseShape(int my_rot[4][5][5]);
~BaseShape();
int rot[4][5][5];
int i_rot;
};
class SquareShape : public BaseShape
{
public:
SquareShape();
~SquareShape();
};
我想在Squareshape类中设置ROT成员的值。我已经尝试了几件事,例如在派生的类构造器中分配它(然后了解您无法分配数组),在Squareshape初始化器列表中设置它(然后了解到您无法在派生类'initializer中初始化suber类'成员'),并将数组传递到基类构造函数,并将成员初始化为参数,该参数无法与错误编译:
error: invalid conversion from ‘int (*)[5][5]’ to ‘int’ [-fpermissive]
rot{my_rot}
所以我想知道是否真的有一种实现此目的的方法,或者是否有更简单的方法可以解决。
c-array不可复制,您可以使用 std::array
代替
using Rot = std::array<std::array<std::array<int, 5>, 5>, 4>;
class BaseShape
{
public:
BaseShape();
BaseShape(Rot my_rot) : rot(my_rot) {}
~BaseShape();
Rot rot;
int i_rot = 0;
};
然后了解到您不能在派生类'initializer
中初始化基类的成员
...杰出的说法是真的,但是您可以称呼适当的构造函数,而不是直接初始化类成员:
#include <iostream>
struct Base {
int x;
Base(int a) : x(a) {}
};
struct Foo : Base {
Foo(int a) : Base(a) {}
};
int main() {
Foo f(1);
std::cout << f.x << "n";
}
故意使用一个没有数组的示例,因为一旦您使用std::array
或std::vector
,数组将不再是问题。