【发布时间】: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<R,C2> result。 result 成为类的外部对象。所以我无法使用result._mat[r*C2+c] 访问它的私有成员。
在这个类中定义我的矩阵乘法函数的解决方案是什么(不改变访问权限)?
【问题讨论】:
-
您应该能够从同一个类中访问另一个对象的私有成员。那么 result._mat[r*C2+c] 应该真的有效吗?
-
@Richard
result._mat[r*C2+c]在这种情况下在 VS2013 上不起作用。 “访问另一个对象的私有成员”是什么意思? -
但如果您有不同的模板(具有不同的模板参数),那么编译器不会将其视为“同一类”
-
@Shindou
Matrix< int R, int C>和Matrix< int R2, int C>不是同一类型。仅仅因为模板是Matrix并不能使类型相同。所以你需要重新考虑你的设计。
标签: c++ class templates c++11 matrix