本人在学习C++面向对象编程时的练习笔记,涉及到类对象、运算符重载、自定义数据类型运算等操作。
代码:
#include <iostream>
#include <cmath>
#include <Windows.h>
using namespace std;
//复数相关计算器
class Complex {
private:
double real; //实部
double imag; //虚部
public:
friend ostream& operator<<(ostream& cout, Complex& c);
Complex(double r, double i);
Complex(const Complex &c);
~Complex() {};
Complex(double r); //虚部操作
Complex operator+(const Complex& c);
Complex operator-(const Complex& c);
Complex operator*(const Complex& c);
Complex operator/(const Complex& c);
inline double getR() { return this->real; }
inline double getI() { return this->imag; }
inline double CX(double r) { this->real = r; }
inline double CY(double i) { this->imag = i; }
};
ostream &operator<<(ostream& cout, Complex& c) {
cout << "(" << c.getR() << "," << c.getI() << ")";
return cout;
}
Complex::Complex(double r, double i):real(r),imag(i){}
Complex::Complex(const Complex& c) {
this->real = c.real;
this->imag = c.imag;
}
Complex::Complex(double r) {
this->imag = 0;
this->real = r;
}
Complex Complex::operator+(const Complex& c) {
return Complex(this->real + c.real, this->imag + c.imag);
}
Complex Complex::operator-(const Complex& c) {
return Complex(this->real - c.real, this->imag - c.imag);
}
Complex Complex::operator*(const Complex& c) {
return Complex(real * c.real - imag * c.imag, real * c.imag + c.real * imag);
}
Complex Complex::operator/(const Complex& c) {
return Complex((double)(real * c.real + imag * c.imag) / (double)(c.real * c.real + c.imag * c.imag),
(double)(imag * c.real - real * c.imag) / (double)(c.real * c.real + c.imag * c.imag));
}
Complex CPower(Complex& c, unsigned n) { //暴力方法
Complex resu(c);
for (n; n > 1; n--) {
resu = resu * c;
}
return resu;
}
Complex ComplexPower(Complex c1, double n) { //利用棣莫弗公式求乘方
double abs_c1 = sqrt(c1.getR() * c1.getR() + c1.getI() * c1.getI());
double theta = atan(c1.getI() / c1.getR());
cout << abs_c1 << endl;
theta = theta*n;
abs_c1 = pow(abs_c1, n);
cout << abs_c1 << "\tcos(theta) = " << cos(theta) << "\tsin(theta) = " << sin(theta) << endl;
return Complex(abs_c1 * cos(theta), abs_c1 * sin(theta));
}
int main() {
Complex c1(1, 2);
Complex c2(0.3,-1.3);
Complex cr = CPower(c1, 5);
cout << "cr = (" << cr.getR() << "," << cr.getI() << ")" << endl;
Complex cr2 = ComplexPower(c2, 3);
cout << "cr2 = (" << cr2.getR() << "," << cr2.getI() << ")" << endl;
cout << pow(1.23, 3.01) << endl;
//框架:构造出来两个复数,利用运算符重载输出加减乘除
// 利用虚函数继承计算传入的实数和复数的运算
Complex cr3 = c1 + c2;
cout << cr3 << endl;
system("pause");
return 0;
}