【发布时间】:2016-02-16 08:28:21
【问题描述】:
我在为矩阵类实现赋值运算符时遇到了一些麻烦。似乎编译器不想识别我的重载赋值运算符(我认为?),我不知道为什么。我知道有一些关于在 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);
【问题讨论】:
-
去掉头文件中声明前面的朋友。
-
friend Matrix& Matrix::operator=(const Matrix& m);什么?为什么?另外请发minimal reproducible example不带行号,方便复制。 -
“朋友……你一直在用这个词。我不认为它意味着你认为它的意思。”
-
类中唯一应该声明为友元运算符的方法是与 ostream 对象一起使用的流运算符。与类本身有关的所有其他运算符都不能成为朋友。但是,如果您想要更快的实现,那么您可以将您的运算符声明为内联!
-
啊,我明白了。一位朋友在帮助我时建议添加“朋友”,我并没有真正质疑它,但我继续删除它们,因为它们是多余的。
标签: c++ class matrix operator-overloading assignment-operator