问:定义并实现一个类 Myst,使下列语句能够正常运行。 Myst x(3.2), y(5,5), z(0.0); z = 8.9 – y;
y = x – 6.3;
答:
#include <iostream>
using namespace std;
//复数类
class Myst {
public:
Myst() : m_real(0.0), m_imag(0.0) { }
Myst(double real, double imag) : m_real(real), m_imag(imag) { }
Myst(double real) : m_real(real), m_imag(0.0) { } //转换构造函数
public:
friend Myst operator-(const Myst &a, const Myst &b);
public:
double real() const { return m_real; }
double imag() const { return m_imag; }
private:
double m_real; //实部
double m_imag; //虚部
};
//重载-运算符
Myst operator-(const Myst &a, const Myst &b) {
Myst c;
c.m_real = a.m_real - b.m_real;
c.m_imag = a.m_imag - b.m_imag;
return c;
}
int main() {
Myst x(3.2), y(5, 5), z(0.0);
z = 8.9 - y;
y = x - 6.3;
return 0;
}