重载运算符的复合语句不起作用(C++)
Compound Statements with Overloaded operators not working(C++)
我正在用 C++ 制作一个 class 矩阵,但在测试中,我发现像
这样的语句
cout << M1; //M1 is object of class Matrix
正在工作,但其他人喜欢
cout << M1 + M2; //M1 and M2 of class matrix
给我错误。我关注的重载函数有这些原型:
//for matrix addition
Matrix operator+(Matrix& m)
//for stream insertion operator
ostream& operator<<(ostream& out, Matrix & m)
你们能帮我看看我错在哪里吗?如果需要,我可以 post 实际代码。
临时对象不能绑定到非常量左值引用。这是临时的:
M1 + M2
并且您的运算符将非常量引用作为第二个参数。您可以通过将其更改为 const
:
来解决此问题
ostream& operator<<(ostream& out, const Matrix & m)
当你这样做时,你可以更改 operator+
的参数并使其成为常量。 operator+
修改任一操作数都没有意义:
Matrix operator+(const Matrix& m) const
像这样声明运算符
ostream& operator<<(ostream& out, const Matrix & m );
^^^^^^^^^^^^^^^^
问题是这个运算符
Matrix operator+(Matrix& m);
returns临时对象和临时对象不能与非常量引用绑定。
我正在用 C++ 制作一个 class 矩阵,但在测试中,我发现像
这样的语句cout << M1; //M1 is object of class Matrix
正在工作,但其他人喜欢
cout << M1 + M2; //M1 and M2 of class matrix
给我错误。我关注的重载函数有这些原型:
//for matrix addition
Matrix operator+(Matrix& m)
//for stream insertion operator
ostream& operator<<(ostream& out, Matrix & m)
你们能帮我看看我错在哪里吗?如果需要,我可以 post 实际代码。
临时对象不能绑定到非常量左值引用。这是临时的:
M1 + M2
并且您的运算符将非常量引用作为第二个参数。您可以通过将其更改为 const
:
ostream& operator<<(ostream& out, const Matrix & m)
当你这样做时,你可以更改 operator+
的参数并使其成为常量。 operator+
修改任一操作数都没有意义:
Matrix operator+(const Matrix& m) const
像这样声明运算符
ostream& operator<<(ostream& out, const Matrix & m );
^^^^^^^^^^^^^^^^
问题是这个运算符
Matrix operator+(Matrix& m);
returns临时对象和临时对象不能与非常量引用绑定。