C++基础练习-类与对象
创建一个复数类complex,私有成员包括实部real和虚部imag,初始化使用
init成员函数,计算幅值使用amplitude成员函数,计算相角使用phase成员函数,
同时为complex定义加减乘除四则运算函数。
#include<iostream>
#include<math.h> //包含pow(double,double),sqrt(double),atan(double)函数
using namespace std;
class Complex {
public:
void init() { //自建init初始化函数初始化复数的实部和虚部
cout << "Please enter the real and imaginary parts of a complex number:" << endl;
cin >> real;
cin >> imag;
}
void amplitude(); //计算幅值和相角的两个成员函数
void phase();
void dp() { //输出复数属性的函数
cout << "real: " << real << " imag: " << imag;
cout << endl; amplitude(); phase(); cout << endl;
}
Complex operator+(Complex&col1); //为complex定义加减乘除四则运算(运算符重载)
Complex operator-(Complex&col1);
Complex operator*(Complex&col1);
Complex operator/(Complex&col1);
private:
double real, imag;
};
void Complex::amplitude() { //类外计算幅值,函数pow(x, y)计算x的y次幂,sqrt()为开方函数
cout << "The amplitude of the complex number is " << sqrt(pow(real, 2) + pow(imag, 2)) << endl;
}
void Complex::phase() { //计算相角,用到了反正切函数atan()
if (real == 0 && imag == 0)
cout << "Calculated phase nonsense!" << endl;
else
if (real > 0) {
cout << "The phase of the complex number is " << atan(imag / real) << "degress." << endl;
}
else
if (real = 0)
cout << "The phase of the complex number is 90 degrees or -90 degrees." << endl;
else
if (real < 0 && imag != 0) {
double deg1 = atan(imag / real) + 180;
double deg2 = atan(imag / real) - 180;
cout << "The phase of the complex number is " << deg1 << " degress or " << deg2 << " degress." << endl;
}
else {
cout << "The phase of the complex number is 180 degrees" << endl;
}
}
Complex Complex::operator+(Complex&col1) //+ - * /四则运算(运算符重载)
{
Complex col;
col.real = real + col1.real;
col.imag = imag + col1.imag;
return col;
}
Complex Complex::operator-(Complex&col1)
{
Complex col;
col.real = real - col1.real;
col.imag = imag - col1.imag;
return col;
}
Complex Complex::operator*(Complex&col1)
{
Complex col;
col.real = real * col1.real;
col.imag = imag * col1.imag;
return col;
}
Complex Complex::operator/(Complex&col1)
{
Complex col;
col.real = real / col1.real;
col.imag = imag / col1.imag;
return col;
}
int main() { //定义六个复数对象对成员函数进行验证
Complex col1; col1.init(); col1.dp();
Complex col2; col2.init(); col2.dp();
Complex col3; col3 = col1 + col2; col3.dp();
Complex col4; col4 = col1 - col2; col4.dp();
Complex col5; col5 = col1 * col2; col5.dp();
Complex col6; col6 = col1 / col2; col6.dp();
return 0;
}