我在为矩阵类实现赋值运算符时遇到了一些麻烦。似乎编译器不想识别我的重载赋值运算符(我想?),我不知道为什么。我知道有一些关于在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);
答案 0 :(得分:2)
您的赋值运算符应该是成员函数,而不是friend
。您的其他运算符应将参数设为const Matrix &
,否则您将复制运算符使用的Matrix对象。
答案 1 :(得分:2)
您正在获取该元素的地址:
&p[x][y] = m.Element(x,y);
当你想要分配给它时,像这样:
p[x][y] = m.Element(x,y);
答案 2 :(得分:1)
friend Matrix& Matrix::operator=(const Matrix& m);
由于必须将operator=
定义为类中的成员函数,因此上述部分没有多大意义。
实际上,如果你在这里避免了对朋友的需求(或者至少有这么多人),我认为你的生活将会轻松得多。矩阵的自给自足的公共接口应该允许您实现所有期望的运算符,无论他们是否是该类的成员。
也许您应该首先寻求的是自给自足的公共界面,这样您实际上并不需要像矩阵乘法运算符这样的东西成为朋友,因为否则可能的诱惑就是让每个操作都涉及到矩阵需要访问矩阵内部。