【问题标题】:Matrix Multiplication with template parameters in C++C++中带有模板参数的矩阵乘法
【发布时间】:2015-07-14 11:44:30
【问题描述】:

我有一个自定义的Matrix类,想重载运算符*做矩阵乘法:

template< int R, int C> 
class Matrix{
   int *_mat;
   int _size;
public:
   Matrix(){ _size = R*C; _mat = new int[_size]{0}; }
   ~Matrix(){ delete []_mat; }
   Matrix &operator=(const Matrix & m){/*...*/}
   //...
   template< int D2, int D1 > using matrix_t = int[D2][D1];
   template<int R2, int C2>
   Matrix<R,C2> operator*(const matrix_t<R2,C2> &mat)
   {
       Matrix<R,C2> result;
       for(int r = 0; r < R; r++)
       {
           for(int c = 0; c < C2; c++)
           {
               for( int i; i < C; i++ ){
                  /*do multiplication...
                    result._mat[r*C2+c] = ...
                  */
               }
           }
       }
       return result;
   }      
   //...
}; 

那么问题来了Matrix&lt;R,C2&gt; resultresult 成为类的外部对象。所以我无法使用result._mat[r*C2+c] 访问它的私有成员。

在这个类中定义我的矩阵乘法函数的解决方案是什么(不改变访问权限)?

【问题讨论】:

  • 您应该能够从同一个类中访问另一个对象的私有成员。那么 result._mat[r*C2+c] 应该真的有效吗?
  • @Richard result._mat[r*C2+c] 在这种情况下在 VS2013 上不起作用。 “访问另一个对象的私有成员”是什么意思?
  • 但如果您有不同的模板(具有不同的模板参数),那么编译器不会将其视为“同一类”
  • @Shindou Matrix&lt; int R, int C&gt;Matrix&lt; int R2, int C&gt; 不是同一类型。仅仅因为模板是Matrix 并不能使类型相同。所以你需要重新考虑你的设计。

标签: c++ class templates c++11 matrix


【解决方案1】:

您可以指定一个运算符,以便在外部设置矩阵的值。请注意,您将无法使用 operator [] - 因为您只能将其与一个参数一起使用(参考 C++ [] array operator with multiple arguments?

   int& operator() (int row, int col) { 
     // todo: check array bounds
     return _mat[C*row+col];
   }

用法:

 result(r,c) = ...

【讨论】:

    【解决方案2】:

    你不能,你可以写像set这样的函数

    void set(int index, int value)
    {
       // check index
       _mat[index] = value;
    }
    

    然后在乘法函数中调用result.set(...)。而不是

    result._mat[r*C2+c] = ...
    

    只是

    result.set(r*C2+c, ...);
    

    这种情况是因为ResultMatrix&lt;R, C2&gt;类型的对象,与Matrix&lt;R, C&gt;的类型不同,所以不能在Matrix&lt;R, C&gt;类型的成员函数中访问Matrix&lt;R, C2&gt;类型的私有成员。

    【讨论】:

    • 您的示例中*this 的类型是Matrix&lt;R,C&gt;,因此无法分配给result...
    • result._mat[...] = value; in void set(int, int, int) 然后打电话给result.set(..)?不知怎的,我无法理解这种用法​​......
    • 我对函数void set(int, int, int) 中的result 感到困惑,因为它既没有在函数内部声明也没有通过参数列表传递......顺便说一下,我认为@Richard 只是给出了一个很好的方法..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多