我编写了一个Matrix
类。它在矩阵之间进行乘法。有时,矩阵相乘会产生 1x1 矩阵(例如,两个列 vector 的内积)。是否可以让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);
如果结果不是一一对应,抛出异常也是可以的。
最佳答案
是的。
这与std::vector::at()
类似。 ,这也是一个编译时调用,除非满足某些运行时条件,否则总是会抛出异常。
类型 T
的转换运算符如下所示:
template <class T> class Matrix
{
public:
// ...
operator T &() {
// Throw here if size is not 1x1...
return (*this)( 0, 0 );
}
operator T const &() const {
// Throw here if size is not 1x1...
return (*this)( 0, 0 );
}
// ...
};
您的所有示例代码都可以按编写的那样工作。
关于c++ - 当矩阵对象的尺寸为 1x1 时,如何使其隐式转换为标量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14490288/