如果是下面这样
c3 = c1 + 11.0;
cout << "+:\t"; c3.display();
c3 = 11.0 + c2;
cout << "+:\t"; c3.display();
就会报错
按上面4.2.cpp改
double i = 11;
c3 = c1 + c2;
cout << "+:\t"; c3.display();
c3 = c1 + i;
cout << "+:\t"; c3.display();
c3 = i + c2;
cout << "+:\t"; c3.display();
就可以通过编译。
原因现在不清楚。。。。。
下面是源码。
operator.h
class Complex
{
public:
double real;
double imag;
void display();
Complex(double r, double i) :real(r), imag(i) {}
Complex() { real = 0; imag = 0; }
friend Complex operator +(Complex &, Complex &);
friend Complex operator +(double &, Complex &);
friend Complex operator +(Complex &, double &);
};
operator.cpp
#include<iostream>
#include"operator_+-.h"
using namespace std;
Complex operator +(Complex &a, Complex &b)
{
return Complex(a.real + b.real, a.imag + b.imag);
}
Complex operator +(double &a, Complex &b)
{
return Complex(a + b.real, b.imag);
}
Complex operator +(Complex &a, double &b)
{
return Complex(a.real + b, a.imag);
}
void Complex::display()
{
cout << "(" << real;
if (imag >= 0)
cout << "+";
cout<< imag << "i)" << endl;
}
4.2.cpp
include
include”operator_+-.h”
using namespace std;
int main()
{
Complex c1(1, 2), c2(3, 2), c3;
double i = 11;
c3 = c1 + c2;
cout << “+:\t”; c3.display();
c3 = c1 + i;
cout << “+:\t”; c3.display();
c3 = i + c2;
cout << “+:\t”; c3.display();
system(“pause”);
return 0;
}