实验一 类与对象 task3 Complex类
2021/10/23 23:11:38
本文主要是介绍实验一 类与对象 task3 Complex类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#include<iostream> #include<cmath> using namespace std; class Complex { private: double real; double imag; public: Complex(double x = 0, double y = 0) :real(x), imag(y) {} Complex(Complex& p); double get_real() const; double get_imag() const; void show()const; void add(const Complex& p); friend Complex add(const Complex& a, const Complex& b); friend bool is_equal(const Complex& a, const Complex& b); friend double abs(Complex& a); }; Complex::Complex(Complex& p) { real = p.real; imag = p.imag; } double Complex::get_real()const { return real; } double Complex::get_imag()const { return imag; } void Complex::show()const { cout << real; if (imag < 0) cout << imag << 'i'; else if (imag > 0) cout << ' + ' << imag << 'i' ; } void Complex::add(const Complex& p) { real += p.real; imag += p.imag; } Complex add(const Complex& a, const Complex& b) { Complex c; c.real = a.real+ b.real; c.imag = a.imag+ b.imag; return c; } bool is_equal(const Complex& a, const Complex& b) { if (a.real == b.real && a.imag == b.imag) return true; else return false; } double abs(Complex& a) { return sqrt(a.real * a.real + a.imag * a.imag); }
#include "Complex.hpp" #include <iostream> #include<cmath> int main() { using namespace std; Complex c1(3, -4); const Complex c2(4.5); Complex c3(c1); cout << "c1 = "; c1.show(); cout << endl; cout << "c2 = "; c2.show(); cout << endl; cout << "c2.imag = " << c2.get_imag() << endl; cout << "c3 = "; c3.show(); cout << endl; cout << "abs(c1) = "; cout << abs(c1) << endl; cout << boolalpha; cout << "c1 == c3 : " << is_equal(c1, c3) << endl; cout << "c1 == c2 : " << is_equal(c1, c2) << endl; Complex c4; c4 = add(c1, c2); cout << "c4 = c1 + c2 = "; c4.show(); cout << endl; c1.add(c2); cout << "c1 += c2, " << "c1 = "; c1.show(); cout << endl; }
这篇关于实验一 类与对象 task3 Complex类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23增量更新怎么做?-icode9专业技术文章分享
- 2024-11-23压缩包加密方案有哪些?-icode9专业技术文章分享
- 2024-11-23用shell怎么写一个开机时自动同步远程仓库的代码?-icode9专业技术文章分享
- 2024-11-23webman可以同步自己的仓库吗?-icode9专业技术文章分享
- 2024-11-23在 Webman 中怎么判断是否有某命令进程正在运行?-icode9专业技术文章分享
- 2024-11-23如何重置new Swiper?-icode9专业技术文章分享
- 2024-11-23oss直传有什么好处?-icode9专业技术文章分享
- 2024-11-23如何将oss直传封装成一个组件在其他页面调用时都可以使用?-icode9专业技术文章分享
- 2024-11-23怎么使用laravel 11在代码里获取路由列表?-icode9专业技术文章分享
- 2024-11-22怎么实现ansible playbook 备份代码中命名包含时间戳功能?-icode9专业技术文章分享