我在为矩阵类实现赋值运算符时遇到一些问题。编译器似乎不想识别我的重载赋值运算符(我认为?),我不确定为什么。我知道有一些关于在 C++ 中实现矩阵类的各种问题的互联网文章(这些文章帮助我走到了这一步),但这次我似乎无法将我当前的困境与现有的任何其他帮助相提并论。不管怎样,如果有人能帮助解释我做错了什么,我将不胜感激。谢谢!
这是我的错误消息:
In file included from Matrix.cpp:10:
./Matrix.h:20:25: error: no function named 'operator=' with type 'Matrix &(const Matrix &)'
was found in the specified scope
friend Matrix& Matrix::operator=(const Matrix& m);
^
Matrix.cpp:79:17: error: definition of implicitly declared copy assignment operator
Matrix& Matrix::operator=(const Matrix& m){ //m1 = m2
^
Matrix.cpp:89:13: error: expression is not assignable
&p[x][y] = m.Element(x,y);
~~~~~~~~ ^
3 errors generated.
这是我的 .cpp 文件中的赋值运算符代码:
Matrix& Matrix::operator=(const Matrix& m){ //m1 = m2
if (&m == this){
return *this;
}
else if((Matrix::GetSizeX() != m.GetSizeX()) || (Matrix::GetSizeY()) != m.GetSizeY()){
throw "Assignment Error: Matrices must have the same dimensions.";
}
for (int x = 0; x < m.GetSizeX(); x++)
{
for (int y = 0; y < m.GetSizeY(); y++){
&p[x][y] = m.Element(x,y);
}
}
return *this;
这是我的矩阵头文件:
class Matrix
{
public:
Matrix(int sizeX, int sizeY);
Matrix(const Matrix &m);
~Matrix();
int GetSizeX() const { return dx; }
int GetSizeY() const { return dy; }
long &Element(int x, int y) const ; // return reference to an element
void Print() const;
friend std::ostream &operator<<(std::ostream &out, Matrix m);
friend Matrix& Matrix::operator=(const Matrix& m);
long operator()(int i, int j);
friend Matrix operator*(const int factor, Matrix m); //factor*matrix
friend Matrix operator*(Matrix m, const int factor); //matrix*factor
friend Matrix operator*(Matrix m1, Matrix m2); //matrix*matrix
friend Matrix operator+(Matrix m1, Matrix m2);
最佳答案
您的赋值运算符应该是成员函数,而不是友元
。您的其他运算符应将参数设为 const Matrix &
,否则您将复制该运算符使用的 Matrix 对象。
关于C++矩阵类: overloading assignment operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33715077/