这是我在学习 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 给出了这些错误:
error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'|
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 运算符有一些应该遵循的特殊规则,以便与(重载的)递增/递减运算符一起使用。
问题:
这是真的吗,还是我没有捕捉到的代码有问题?我是这个领域的初学者。
重载输出/输入运算符和递增(post,pre)/递减运算符是否有一些额外的规则可以一起使用?
P.S.:请原谅我的英语不好......谢谢
最佳答案
我没有遇到与您相同的错误,但这肯定是一个问题:
ostream& operator<<(ostream &out, Complex &a);
Complex operator++(int);
cout << c++;
您已声明 operator<<
采取它的Complex
通过对非常量的引用的参数,然后尝试将临时绑定(bind)到该引用。临时对象不能绑定(bind)到非常量引用。
解决这个问题的简单方法是声明您的运算符(operator)接受 a
通过 reference-to-const 以便右值可以绑定(bind)到它:
ostream& operator<<(ostream &out, const Complex &a);
关于c++ - 重载 I/O 流运算符和前/后递增/递减运算符错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32476168/