c++ - 将矩阵传递给函数

标签 c++ matrix constructor

  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/

相关文章:

c++ - 在有效类型和无效类型之间进行选择

c++ - Vim YouCompleteMe 配置

iPhone:如何使用CGContextConcatCTM正确保存转换后的图像?

java - 构造函数 SignalStrength() 不可见?该怎么办?

javascript - ES6 构造函数返回基类的实例?

java - 添加与其他构造函数类似的构造函数意味着什么?

c++ - 使用 PowerShell 作为控制台,就好像它是使用 AllocConsole 创建的一样

file - matlab 垂直串联

python - numpy 将 RGB 图像转换为 YIQ 颜色空间

c++ - 为什么所有 C++ 编译器都会因为这段代码而崩溃或挂起?