C++ C++;,矩阵运算,算子问题
我的课程中有一部分是关于矩阵运算的:C++ C++;,矩阵运算,算子问题,c++,matrix,operators,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
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
...
};
到矩阵B
Matrix <int> B (2,2);
B = A; //Compiler error, see bellow, please
但编译器显示此错误:
Error 23 error C2446: '!=' : no conversion from 'const Matrix<T> *' to 'Matrix<T> *const '
错误23错误C2446:'!=':没有从“常数矩阵*”到“矩阵*常数”的转换
感谢您的帮助…您演示的代码中有一些错误,但您应该计算出您演示的代码片段,因为错误似乎指向使用了
运算符=代码>,而代码使用运算符=
和运算符+
现在讨论一些特定问题:您正在声明一个定义不同运算符的
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
// ^
模板
类矩阵{
...
模板
矩阵算子+(矩阵常数&)常数;
// ^
};
模板
模板
矩阵::运算符+(矩阵常数&m)常数
// ^
另外,一般来说,根据经验法则在类声明中定义模板成员更容易。这实际上与您遇到的问题无关,但在您真正开始提供确切的错误之前,请先提供所涉及的错误行和代码(还请注意,如果您可以在不使用多个已定义运算符的行中重现错误,效果会更好)。。。好吧,如果没有更多的细节,我真的帮不了什么忙。正如其他人所指出的,很难知道问题是什么,因为您没有提供产生错误的案例的实现,“!=”,也不是“=”的。我的猜测是,问题源于您的const data成员。这可能导致编译器将矩阵类的所有实例解释为常量对象,这将导致错误消息。当然,如果赋值运算符没有考虑到这一点,那么任何赋值都会失败,尽管这样的代码可能无法编译,而您的代码则会
所以:拿出常数,看看会发生什么
而且
C ( i, j ) = items[i][j] + M.items[i][j]
应该是
C.items[i][i] = items[i][j] + M.items[i][j]
实际上,您没有将实现发布到任何产生错误的函数。@DeadMG:运算符+代码中有一个输入错误,我更正了它……错误消息引用的指针完全不在您提供的代码中。请注意,const Matrix*
等同于Matrix const*
而不是Matrix*const
@AProgrammer:谢谢您的评论。。。但是如何解决这个问题,我可以要求您提供一个简短的代码示例吗?另一个问题是C(I,j)=items[I][j]+M.items[I][j];当C.items[i][j]=。。。是有意的。说你用另一个操作员解决了问题(而不是从一开始就有问题的操作员)几乎没有帮助。您至少应该提供问题和解决方案,以便其他人能够从中学习。这就是只有一半代码的问题。我假设既然项
是私有的,他可能已经为成员访问提供了操作符()(int,int)
(或类似的东西),他会使用它。但在一天结束时,作业的双方看起来应该相似(要么都是[][]
,要么都是(,)
)
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 ( i, j ) = items[i][j] + M.items[i][j]
C.items[i][i] = items[i][j] + M.items[i][j]