2011-04-25 111 views
0

有我的课的矩阵操作的一部分:C++,矩阵运算,与运营商的问题

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

你实际上并没有发布实施,任何能产生一个错误的功能。 – Puppy 2011-04-25 19:54:53

+0

@DeadMG:运营商+代码中存在拼写错误,我纠正了它... – Robo 2011-04-25 19:59:22

+1

错误消息引用的指针完全缺少您提供的代码。注意'const Matrix *'相当于'Matrix const *'而不是'Matrix * const'。 – AProgrammer 2011-04-25 20:01:57

回答

1

有在代码中的一些错误,你呈现,但是您应该计算出您提供的代码片段,因为错误似乎指向使用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 
// ^

而且,在一般情况下,它更容易定义类的声明作为一个经验法则里面的模板成员。这实际上与您所遇到的问题无关,但在您真正了解提供确切的错误之前,需要涉及错误行和代码(还请注意,如果您可以在一行中重现错误不要使用多于一个定义的运算符)...好吧,没有更多的细节我真的帮不了多少忙。

+0

另一个问题是C(i,j)= items [i] [j] + M.items [i] [j]; 肯定C.items [i] [j] = ...的意图。 – 2011-04-25 21:01:54

+0

我解决了operator =中的问题,并且它可以工作... – Robo 2011-04-25 21:25:58

+1

说你在不同的操作员(比你遇到的问题开始时)解决了问题几乎没有任何帮助。你至少应该提供什么问题和解决方案,以便其他人通过SO来学习。 – 2011-04-26 07:26:19

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] 
+0

这是只有一半代码的问题。我假设'items'是私有的,他可能已经提供了'operator()(int,int)'(或类似的东西)用于成员访问,他会使用它。但是在一天结束时,任务的两边应该看起来相似(或者是[] []'或者都是'(,)') – 2011-04-26 07:24:43