使用 QGenericMatrix 作为另一个类的属性

Using a QGenericMatrix as an attribute for another class

本文关键字:属性 另一个 QGenericMatrix 使用      更新时间:2023-10-16

Qt有一个名为QGenericMatrix的类。它的定义如下:

template <int N, int M, typename T>
class QGenericMatrix
{...}

我想将其用作我自己MyClass类中的属性colorMatrix,然后像这样在其构造函数中初始化它:

MyClass::MyClass(int n, int m)
{
colorMatrix = new QGenericMatrix<n, m, QColor>;
}

但是,语法可能非常不正确。我应该如何在头文件和构造函数中编写声明?

由于模板参数必须在编译时已知,因此您有两种选择:

  1. 在 MyClass 中修复矩阵大小和类型,例如

    class MyClass {
    QGenericMatrix<2, 3, QColor> colorMatrix;
    }
    
  2. 将 MyClass 定义为采用与 QGenericMatrix 相同的模板参数的模板,并使用 MyClass 的模板参数实例化 colorMatrix。这样:

    template<int N, int M, typename T>
    class MyClass {
    MyClass() { // init }
    T entry(int i, int j);
    QGenericMatrix<N, M, T> colorMatrix;
    }
    template<int N, int M, typename T>
    T MyClass::entry(int i, int j) { return colorMatrix(i, j); }
    

    当然,在这种情况下,MyClass 必须使用模板参数进行实例化,这些参数必须在编译时再次知道。

    MyClass<2, 3, QColor> myClass;