实验4
不使用C++标准库,自行设计并实现一个简化版复数类Complex.
1 #pragma once 2 #include<bits/stdc++.h> 3 using namespace std; 4 class Complex 5 { 6 public: 7 Complex(double a=0, double b=0) :real{ a }, imag{ b }{}; 8 Complex(const Complex& c) :real{ c.real }, imag{ c.imag }{}; 9 double get_real()const { return real; } 10 double get_imag()const { return imag; } 11 void show()const; 12 void add(const Complex& c); 13 friend Complex add(const Complex& c1, const Complex& c2); 14 friend bool is_equal(const Complex& c1, const Complex& c2); 15 friend double abs(Complex& c); 16 private: 17 double real; 18 double imag; 19 }; 20 void Complex::show()const { 21 if (imag > 0) 22 cout << real << "+" << imag << "i"; 23 if (imag < 0) 24 cout << real << imag << "i" ; 25 if (imag == 0) 26 cout << real ; 27 } 28 void Complex::add(const Complex& c) { 29 real += c.real; 30 imag += c.imag; 31 } 32 Complex add(const Complex& c1, const Complex& c2) { 33 Complex c; 34 c.real = c1.real + c2.real; 35 c.imag = c1.imag + c2.imag; 36 return c; 37 } 38 bool is_equal(const Complex& c1, const Complex& c2) { 39 if (c1.real == c2.real && c1.imag == c2.imag) 40 return true; 41 else 42 return false; 43 } 44 double abs(Complex& c) { 45 double ans; 46 ans = sqrt(c.real * c.real + c.imag * c.imag); 47 return ans; 48 }
#include "Complex.hpp" #include <iostream> // 类测试 void test() { 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; } int main() { test(); }
标签:real,const,对象,double,imag,Complex,实验,void From: https://www.cnblogs.com/zhouxv/p/16784952.html