c++ - 当矩阵对象的尺寸为 1x1 时,如何使其隐式转换为标量?

标签 c++ matrix operator-overloading member-functions

我编写了一个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];
}

// ...

示例代码:

Latex image

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/

相关文章:

c++ - 重载运算符<<(unsigned char typedef as byte)

c++ - 在 C++ 中返回一个全局数组

c++ - 为什么这个按位运算是 "narrowing conversion from ' int' 到 'byte'“? - Arduino

r - 在 data.frame 中将列名的所有组合创建为行的有效方法

java - 如何在java中创建动态二维矩阵?

c++ - 这是STL中的错误吗?为什么我们需要在此结构中重载运算符?

c++ - 使用引用变量复制构造函数

c++ - 为什么我的对象的大小没有减小?

python - 使用 numpy 将数组元素添加到矩阵的每一列

c++ - 为什么我的重载 << 不返回任何数据?