Abd*_*een 0 c++ reference class operator-overloading
我在c ++中创建了一个类Matrix,但在测试中,我发现了类似的语句
cout << M1; //M1 is object of class Matrix
Run Code Online (Sandbox Code Playgroud)
正在工作,但其他人喜欢
cout << M1 + M2; //M1 and M2 of class matrix
Run Code Online (Sandbox Code Playgroud)
给我错误.我关心的重载函数有这些原型:
//for matrix addition
Matrix operator+(Matrix& m)
//for stream insertion operator
ostream& operator<<(ostream& out, Matrix & m)
Run Code Online (Sandbox Code Playgroud)
你们可以在我出错的地方帮助我吗?如果需要,我可以发布实际代码.
临时数不能绑定到非常量左值引用.这是暂时的:
M1 + M2
Run Code Online (Sandbox Code Playgroud)
并且您的运算符将非const引用作为第二个参数.您可以通过将其更改为const:
ostream& operator<<(ostream& out, const Matrix & m)
Run Code Online (Sandbox Code Playgroud)
当你在它时,你可以改变参数operator+并使其成为常量.operator+修改任一操作数是没有意义的:
Matrix operator+(const Matrix& m) const
Run Code Online (Sandbox Code Playgroud)