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

时间:2011-04-25 19:40:52

标签: c++ matrix operators

我的班级有一部分用于矩阵运算:

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 '

感谢您的帮助......

2 个答案:

答案 0 :(得分:1)

您提供的代码中存在一些错误,但您应该计算出您提供的代码片段,因为错误似乎指向使用operator!=,而代码使用{{1 }和operator=

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

operator+

此外,通常,根据经验,在类声明中定义模板成员更容易。这实际上与您遇到的问题没有关系,但是在您真正解决提供确切错误之前,包括错误行和涉及的代码(另请注意,如果您可以在一行中重现错误,那就更好了)不要使用超过一个已定义的运算符)...好吧,没有任何更多的细节,我真的不能帮助太多。

答案 1 :(得分:0)

正如其他人所指出的那样,很难知道问题是什么,因为你没有提供产生错误的案例的实现,'!=',也不是'='。我的猜测是问题来自你的const数据成员。这可能导致编译器将Matrix类的所有实例解释为const对象,这将导致您的错误消息。当然,你的任务操作员没有考虑到这一点,那么任何任务都会失败,尽管这样的代码可能无法编译而你的编译也是如此。

所以:取出效果,看看会发生什么。

另外,

C ( i, j ) = items[i][j] + M.items[i][j]

肯定是

C.items[i][i] = items[i][j] + M.items[i][j]