前文:本文不是正确答案,有一个测试点过不去,只是希望后来者可以通过。(8分/10分)
提示:
该题的主函数不对!
所以在外部编译器上可以通过的程序,提交时会显示编译错误。
一、题目
请设计复数类COMPLEX,实现复数的输入、输出和加法运算。
#include <iostream>
#include <iomanip>
using namespace std;
/* 你提交的代码将被嵌在这里 */
int main()
{
COMPLEX a, b, c;
cin >> a >> b;
c = a + b;
cout << c << endl;
return 0;
}
输入样例
3.2+4.9i
2.5-7.3i
输出样例
5.7-2.4i
要求:
1.设计构造函数,达到以下效果。
COMPLEX a;
cout << a << endl; // 输出: 0+0i
COMPLEX a(3);
cout << a << endl; // 输出: 3+0i
COMPLEX a(3, 4);
cout << a << endl; // 输出: 3+4i
2.重载输出运算符函数,达到以下效果。
COMPLEX a(3, 4);
cout << a << endl; // 输出: 3+4i;
COMPLEX a(3, 4), b(2, -7);
cout << a << ' ' << b << endl; // 输出: 3+4i 2-7i
3.重载输入运算符函数,达到以下效果。
COMPLEX a;
cin >> a; // 输入: 3+4i
COMPLEX a, b;
cin >> a >> b; // 输入: 3+4i 2-7i
cout << a << ' ' << b << endl; // 输出: 3+4i 2-7i
4.重载算术加运算符,达到以下效果。
COMPLEX a(3, 4), b(2, -7), c;
c = a + b;
cout << c << endl; // 输出: 5-3i
COMPLEX a(3, 4), b(2, -7), c(-1, 8), d;
d = a + b + c;
cout << d << endl; // 输出: 4+5i
二、解题步骤
1.完全按照题目
class COMPLEX {
private:
double image,real;
public:
COMPLEX(double a= 0,double b= 0) {
real = a;
image = b;
}
COMPLEX operator+(COMPLEX &a)
{
COMPLEX p(real+a.real,image+a.image);
return p;
}
COMPLEX operator-(COMPLEX &a)
{
COMPLEX p(real-a.real,image-a.image);
return p;
}
friend ostream&operator<<(ostream&out,COMPLEX&a) {
out<<a.real;
if(a.image>=0) out<<'+';
out<<a.image<<'i';
return out;
}
friend istream&operator>>(istream&in,COMPLEX&s){
char i;
in>>s.real>>s.image>>i;
return in;
}
};
正如前文,在外部编译器上可以通过的程序,提交时会显示编译错误
2.分析编译器输出
通过那几百行的代码,发现要有重载+且参数为float 与 COMPLEAX才行。
friend COMPLEX operator+(float a,COMPLEX &b)
{
COMPLEX p(a+b.real,a+b.image);
return p;
}
friend COMPLEX operator+(COMPLEX &b,float a)
{
COMPLEX p(a+b.real,a+b.image);
return p;
}
按道理加上以上代码,应该可以通过除最后一个测试点了。Ps:由于题记已关,无法考究。
3.最终结果
经过多次测试,最终代码为:
class COMPLEX {
private:
float image,real;
public:
COMPLEX(float a= 0,float b=0){
real = a;
image = b;
}
COMPLEX operator+( COMPLEX &a){
return COMPLEX(a.real+real,a.image+image);
}
COMPLEX operator-(COMPLEX &a){}
friend COMPLEX operator+(float a,COMPLEX &b){}
friend COMPLEX operator+(COMPLEX &b,float a){}
friend ostream&operator<<(ostream&out,COMPLEX&a) {
out<<a.real;
if(a.image>=0) out<<'+';
out<<a.image<<'i';
return out;
}
friend istream&operator>>(istream&in,COMPLEX&s) {
char sign;
in>>s.real>>s.image;
in>>sign;
return in;
}
};
最后
小有遗憾:到最后也没能通过全部测试点
希望后来者可以通过(可以的话,告诉一声)
祝 好运。
(^U^)ノ~LUCK