我的类(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/