unsigned char j[4][4];
我想将这个元素传递给类的构造函数,我在类中有一个与矩阵类型相同的属性
class x{
private:
unsigned char x[4][4];
public:
x(unsigned char j[4][4]);
};
我将值放入我的矩阵 j 和构造函数中,我想像这样均衡 j 和 x
x(unsigned char j[4][4]){
x = j;
}
但是代码中出现错误
将“unsigned char (*)[4]”赋值给“unsigned char [4][4]”时类型不兼容
为什么?
最佳答案
您不能像这样将数组作为参数传递。您不应该一开始就使用数组。真的,只是不要。您面临的问题只是您在使用数组时会遇到的众多问题中的一个。
相反,使用 std::array
包含另一个 std::array
(因此它是二维的):
#include <array>
class X {
private:
std::array<std::array<unsigned char, 4>, 4> x;
public:
X(std::array<std::array<unsigned char, 4>, 4> j);
};
在你的构造函数中,只需赋值:
X(std::array<std::array<unsigned char, 4>, 4> j)
{
x = j;
}
或者,更好的是,使用 constructor initialization list :
X(std::array<std::array<unsigned char, 4>, 4> j)
: x(j)
{ }
(另请注意,我将您的类名从 x
更改为 X
(大写。)不要对类和变量使用冲突的名称。这很困惑:-)
如果您需要矩阵的大小在运行时确定而不是固定大小,请使用 std::vector
而不是 std::array
。
关于c++ - 将矩阵传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36269414/