Complex类
源码
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
class Complex
{
private:
double real, imaginary;
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imaginary(i){};
Complex(const Complex &c);
void add(const Complex m);
void show();
double mod();
};
Complex::Complex(const Complex &c)
{
real = c.real;
imaginary = c.imaginary;
}
void Complex::add(const Complex m)
{
real += m.real;
imaginary += m.imaginary;
}
void Complex::show()
{
cout << real << std::showpos << imaginary << "i" << std::noshowpos << endl;
}
double Complex::mod()
{
return sqrt(real * real + imaginary * imaginary);
}
int main()
{
Complex c1(3, 5);
Complex c2 = 4.5;
Complex c3(c1);
c1.add(c2);
c1.show();
cout << c1.mod();
return 0;
}
运行截图
按照要求写出的Comloex类有点问题,add函数的设计不合理。
改进
源码
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
class Complex
{
private:
double real, imaginary;
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imaginary(i){};
Complex(const Complex &c);
Complex add(const Complex m);
void show();
double mod();
};
Complex::Complex(const Complex &c)
{
real = c.real;
imaginary = c.imaginary;
}
Complex Complex::add(const Complex m)
{
Complex a;
a.real = real+m.real;
a.imaginary = imaginary+m.imaginary;
return a;
}
void Complex::show()
{
cout << real << std::showpos << imaginary << "i" << std::noshowpos << endl;
}
double Complex::mod()
{
return sqrt(real * real + imaginary * imaginary);
}
int main()
{
Complex c1(3, 5);
Complex c2 = 4.5;
Complex c3(c1);
c1 = c1.add(c2);
c1.show();
cout << c1.mod();
cin.get();
return 0;
}
像这样把结果return
回来才比较好。
感想
无