【问题标题】:Compound Statements with Overloaded operators not working(C++)重载运算符的复合语句不起作用(C++)
【发布时间】:2016-03-22 19:47:43
【问题描述】:

我正在用 C++ 制作一个类 Matrix,但在测试中,我发现像

这样的语句
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)

你们能帮我解决我哪里出错了吗?如果需要,我可以发布实际代码。

【问题讨论】:

  • ostream&amp; operator&lt;&lt;(ostream&amp; out, const Matrix &amp; m)

标签: c++ class reference operator-overloading


【解决方案1】:

临时对象不能绑定到非常量左值引用。这是暂时的:

M1 + M2

并且您的运算符将非常量引用作为第二个参数。您可以通过将其更改为 const 来解决此问题:

ostream& operator<<(ostream& out, const Matrix & m)

当您使用它时,您可以更改operator+ 的参数并将其设为常量。 operator+ 修改任一操作数是没有意义的:

Matrix operator+(const Matrix& m) const

【讨论】:

  • 嗯,解决了这个问题。谢谢你指出(y)
  • 我真的忘了在 operator+ 中让它保持不变。非常感谢。
【解决方案2】:

将操作符声明为like

ostream& operator<<(ostream& out, const Matrix & m );
                                  ^^^^^^^^^^^^^^^^

问题在于这个操作符

Matrix operator+(Matrix& m);

返回一个临时对象,并且临时对象可能不会与非常量引用绑定。

【讨论】:

    猜你喜欢
    • 2013-07-18
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    相关资源
    最近更新 更多