C++,矩阵运算,运算符问题

标签 c++ matrix operators

我的类(class)中有一部分用于矩阵运算:

class Matrix
{
private:
    std::vector < std::vector <T> > items;      
    const unsigned int rows_count;          
    const unsigned int columns_count;       

public:
    Matrix ( unsigned int m_rows, unsigned int m_columns);
    Matrix ( const Matrix <T> &M );

    template <typename U>
    Matrix <T> & operator = ( const Matrix <U> &M );

    template <typename U>
    bool operator == ( const Matrix <U> &M ) const;

    template <typename U>
    bool operator != ( const Matrix <U> &M ) const ;

    template <typename U>
    Matrix <T> operator + ( const Matrix <U> &M ) const
    ...
};

在哪里

template <typename T>
template <typename U>
Matrix <U> Matrix <T> ::operator + ( const Matrix <U> &M ) const
{
    Matrix <U> C ( M );

    for ( unsigned int i = 0; i < rows_count; i++ )
    {
        for ( unsigned int j = 0; j < M.getColumnsCount(); j++ )
        {
                C ( i, j ) = items[i][j] + M.items[i][j];
        }
    }

    return C;
}

template<class T>
Matrix <T> :: Matrix ( const Matrix <T> &M )
    : rows_count ( M.rows_count ), columns_count ( M.columns_count ), items ( M.items ) {}

但是下面的运算符有问题:=, ==, !=

我正在尝试分配矩阵 A

Matrix <double> A (2,2);
Matrix <double> C (2,2);

到矩阵B

Matrix <int> B (2,2);

B = A;  //Compiler error, see bellow, please

其中 A 和 B 具有不同的类型。常见的矩阵运算也会出现同样的情况

C = A + B   //Compiler error, see bellow, please

但是编译器显示这个错误:

Error   23  error C2446: '!=' : no conversion from 'const Matrix<T> *' to 'Matrix<T> *const '

感谢您的帮助...

最佳答案

您提供的代码中有一些错误,但您应该找出您提供的代码片段,因为错误似乎指向使用 operator!=,而代码使用 operator=operator+

现在关于一些特定问题:您正在声明定义不同的运算符:

template <typename T>
class Matrix {
...
   template <typename U>
   Matrix<T> operator+( Matrix<U> const & ) const; 
   //     ^
};
template <typename T>
template <typename U>
Matrix<U> Matrix<X>::operator+( Matrix<U> const & m ) const
//     ^

此外,一般来说,根据经验,在类声明中定义模板成员更容易。这实际上与您遇到的问题无关,但在您真正开始提供确切的错误之前,包括错误行和所涉及的代码(另请注意,如果您可以在行中重现错误会更好不要使用超过一个你定义的运算符)......好吧,没有更多细节我真的帮不上什么忙。

关于C++,矩阵运算,运算符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5782418/

相关文章:

c++ - 如何将多个字符串添加在一起,例如 "123"+"456"?

c++ - 高斯消去码

python - 如何使用 numpy 在二维数组上执行最大/均值池化

javascript - Node.getAttribute 的运算符计算不一致

c++ - 在 C++ 中用类型为 'double' 的乘数将复数对象与实部和虚部相乘

c++ - 如何在屏幕抓取中捕获鼠标光标?

c++ - 是什么导致数组越界运行时错误?

c++ - Qt 如何检查 openUrl() 是否已经打开?在窗口中

arrays - 仅对包含矩阵列表中完整案例的行进行子集化

Lua:获取默认小于数字的函数