我写了一个Matrix
类。它在矩阵之间进行乘法运算。有时矩阵的乘法会产生一个 1x1 矩阵(例如,两个列向量的内积)。是否可以让一个Matrix
对象在一对一的时候直接返回一个标量值?
template <class T> class Matrix
{
public:
// ...
T& operator()(uint64_t unRow, uint64_t unCol = 0) throw(MatrixOutOfRange);
const T& operator()(uint64_t unRow, uint64_t unCol = 0) const throw(MatrixOutOfRange);
// ...
protected:
std::vector<T> MatrixArray;
// ...
};
// ...
template <class T>
T & Matrix<T>::operator()(uint64_t unRow, uint64_t unCol /*= 0*/) throw(MatrixOutOfRange)
{
/* Bound checking here */
return MatrixArray[m_unColSize * unRow + unCol];
}
template <class T>
const T & Matrix<T>::operator()(uint64_t unRow, uint64_t unCol /*= 0*/) const throw(MatrixOutOfRange)
{
/* Bound checking here */
return MatrixArray[m_unColSize * unRow + unCol];
}
// ...
示例代码:
Matrix<double> A (3, 1, 1.0, 2.0, 3.0);
Matrix<double> AT(1, 3, 1.0, 2.0, 3.0); // Transpose of the A matrix
Matrix<double> B (3, 1, 4.0, 5.0, 6.0);
Matrix<double> C();
C = AT * B;
double Result1 = C(0, 0);
double Result2 = (AT * B)(0, 0);
double Result3 = A.InnerProductWith(B)(0, 0);
(0, 0)
当结果是一对一矩阵时,我想删除不必要的元素位置说明符参数。像这样:
C = AT * B;
double Result1 = C;
double Result2 = AT * B;
double Result3 = A.InnerProductWith(B);
如果结果不是一一对应的,抛出异常也没关系。