I/O流操作符和前/后递增/递减操作符重载错误

Overloading I/O streams operator and pre/post-increment/decrement operators error?

本文关键字:操作符 重载 错误      更新时间:2023-10-16

这是我在网站上发现的代码,我正在学习c++。我不知道如何调试程序,所以我不知道问题出在哪里。

#include <iostream>
using namespace std;
class Complex
{
int real;
int img;
public:
Complex()
{
    real = 0;
    img = 0;
}
Complex(int r, int i)
{
    real = r;
    img = i;
}
Complex& operator++();
Complex operator++(int);
friend Complex operator+(Complex &a, Complex &b);
friend ostream& operator<<(ostream &out, Complex &a);
friend istream& operator>>(istream &in, Complex &a);
void display()
{
    using namespace std;
    cout << real << " + " << img << endl;
}
};
Complex& Complex::operator++()
{
    ++real;
    ++img;
    return *this;
}
Complex Complex::operator++(int)
{
    Complex temp(*this);
    ++(*this);
    return temp;
}
Complex operator+(Complex &a, Complex &b)
{
    int x = a.real + b.real;
    int y = a.img + b.img;
    return Complex(x, y);
}
ostream& operator<<(ostream &out, Complex &a)
{
    using namespace std;
    out << a.real << " + " << a.img << endl;
    return out;
}
istream& operator>>(istream &in, Complex &a)
{
    using namespace std;
    cout << "Enter the real part" << endl;
    in >> a.real;
    cout << "Enter the imaginary part" << endl;
    in >> a.img;
    return in;
}
int main()
{
    Complex a;
    cin >> a;
    Complex b(11,8);
    cout << "a is :" << a << endl;
    cout << "b is :" << b << endl;
    Complex c = Complex(a + b);
    cout << "c is :" << c << endl;
    cout << c;
    cout << c++;
    cout << c;
    cout << ++c;
    cout << c;
}

当我试图在main()中增加Complex的实例时,编译器给出了错误。在我看来,一切都是正确的,但是Code::Blocks给出了这些错误:

  1. error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'|

  2. error: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = Complex]|

现在这让我相信(重载)I/O操作符有一些特殊的规则,为了使用(重载)自增/自减操作符,应该遵循这些规则。

问题:

  1. 这是真的,还是我没有捕捉到的代码中有问题?我是这个领域的初学者。

  2. 是否重载输出/输入操作符和自增(post,pre)/自减操作符有一些额外的规则来一起使用它们?

注:如:请原谅我的英语很差谢谢

我没有得到和你一样的错误,但这些肯定是一个问题:

ostream& operator<<(ostream &out, Complex &a);
Complex operator++(int);
cout << c++;

您已经声明operator<<通过引用到非const来获取其Complex参数,然后您尝试将临时引用绑定到该引用。临时变量不能绑定到非const引用。

解决这个问题的简单方法是声明你的操作符通过对const的引用来获取a,这样右值就可以绑定到它:

ostream& operator<<(ostream &out, const Complex &a);

问题是在输出操作符函数中使用了非const引用。这样做的问题是,当您使用后缀自增运算符(c++)时,operator++函数按值返回一个新的Complex对象,该对象是临时,并且您不能将非const引用绑定到临时对象。

简单修复:将实参改为const引用:

ostream& operator<<(ostream &out, const Complex &a) { ... }

在输出操作符重载函数中将形参"Complex &a"设置为const(例如const Complex &a)