primer plus 11章里的一道题:
头文件:
#include
using std::ostream;
using std::istream;
class Cmp
{
private:
double n_real;
double n_imaginary;
public:
Cmp(double real = 0, double imaginary = 0);
~Cmp();
friend Cmp operator+ (const Cmp &a, const Cmp &b);
friend Cmp operator- (const Cmp &a, const Cmp &b);
friend Cmp operator* (const Cmp &a, const Cmp &b);
friend Cmp operator* (double n, const Cmp &cmplx);
friend Cmp operator~ (const Cmp &cmplx);
friend std::istream &operator>> (std::istream &is, Cmp &cmplx);
friend std::ostream &operator<< (std::ostream &os, Cmp &cmplx);
};
函数定义:
#include
#include "cmp.h"
using std::cout;
Cmp::Cmp(double real, double imaginary)
{
n_real = real;
n_imaginary = imaginary;
}
Cmp::~Cmp() {}
Cmp operator+ (const Cmp &a, const Cmp &b)
{
return Cmp(a.n_real + b.n_real, a.n_imaginary + b.n_imaginary);
}
Cmp operator- (const Cmp &a, const Cmp &b)
{
return Cmp(a.n_real - b.n_real, a.n_imaginary - b.n_imaginary);
}
Cmp operator* (const Cmp &a, const Cmp &b)
{
return Cmp(a.n_real * b.n_real - a.n_imaginary * b.n_imaginary,
a.n_real * b.n_imaginary + a.n_imaginary * b.n_real);
}
Cmp operator* (const double n, const Cmp &cmplx)
{
return Cmp(n * cmplx.n_real, n * cmplx.n_imaginary);
}
Cmp operator~ (const Cmp &cmplx)
{
return Cmp(cmplx.n_real, -cmplx.n_imaginary);
}
std::istream &operator>> (std::istream &is, Cmp &cmplx)
{
cout << "real: ";
is >> cmplx.n_real;
cout << "imaginary: ";
is >> cmplx.n_imaginary;
return is;
}
std::ostream &operator<< (std::ostream &os, Cmp &cmplx)
{
os << "(" << cmplx.n_real << ", " << cmplx.n_imaginary << "i)";
return os;
}
应用:
#include
#include "cmp.h"
using namespace std;
int main()
{
Cmp a(3.0, 4.0); // initialize to (3,4i) Programming Exercises
Cmp c;
cout << "Enter a complex number (q to quit):\n";
while (cin >> c)
{
cout << "c is " << c << '\n';
cout << "complex conjugate is " << ~c << '\n';
cout << "a is " << a << "\n";
cout << "a + c is " << a + c << '\n';
cout << "a - c is " << a - c << '\n';
cout << "a * c is " << a * c << '\n';
cout << "2 * c is " << 2 * c << '\n';
cout << "Enter a complex number (q to quit):\n";
}
cout << "Done!\n";
return 0;
}
运行后程序报错 cannot bind 'std::basic_ostream' lvalue to 'std::basic_ostream&&'|
折腾了好长时间都解决不了,代码也感觉没有错误,请问大家到底问题出在哪里?