zoukankan      html  css  js  c++  java
  • Complex类的设计与改进

    Complex类

    源码

    #include <cmath>
    #include <iomanip>
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Complex
    {
      private:
        double real, imaginary;
    
      public:
        Complex(double r = 0.0, double i = 0.0) : real(r), imaginary(i){};
        Complex(const Complex &c);
        void add(const Complex m);
        void show();
        double mod();
    };
    
    Complex::Complex(const Complex &c)
    {
        real = c.real;
        imaginary = c.imaginary;
    }
    
    void Complex::add(const Complex m)
    {
        real += m.real;
        imaginary += m.imaginary;
    }
    
    void Complex::show()
    {
        cout << real << std::showpos << imaginary << "i" << std::noshowpos << endl;
    }
    
    double Complex::mod()
    {
        return sqrt(real * real + imaginary * imaginary);
    }
    
    int main()
    {
        Complex c1(3, 5);
        Complex c2 = 4.5;
        Complex c3(c1);
        c1.add(c2);
        c1.show();
        cout << c1.mod();
        return 0;
    }
    

    运行截图

    按照要求写出的Comloex类有点问题,add函数的设计不合理。

    改进

    源码

    #include <cmath>
    #include <iomanip>
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Complex
    {
    private:
      double real, imaginary;
    
    public:
      Complex(double r = 0.0, double i = 0.0) : real(r), imaginary(i){};
      Complex(const Complex &c);
      Complex add(const Complex m);
      void show();
      double mod();
    };
    
    Complex::Complex(const Complex &c)
    {
      real = c.real;
      imaginary = c.imaginary;
    }
    
    Complex Complex::add(const Complex m)
    {
      Complex a;
      a.real = real+m.real;
      a.imaginary = imaginary+m.imaginary;
      return a;
    }
    
    void Complex::show()
    {
      cout << real << std::showpos << imaginary << "i" << std::noshowpos << endl;
    }
    
    double Complex::mod()
    {
      return sqrt(real * real + imaginary * imaginary);
    }
    
    int main()
    {
      Complex c1(3, 5);
      Complex c2 = 4.5;
      Complex c3(c1);
      c1 = c1.add(c2);
      c1.show();
      cout << c1.mod();
      cin.get();
      return 0;
    }
    

    像这样把结果return回来才比较好。

    感想

  • 相关阅读:
    Node项目
    Angular模块/服务/MVVM
    Angular介绍1
    Node环境配置及Gulp工具
    Linux及Git介绍
    数据库MySQL
    ReactiveCocoa 监听枚举类型enumerate 或者 NSInteger类型
    ReactiveCocoa 监听布尔(BOOL)类型改变
    python3.7 urlopen请求HTTPS警告'CERTIFICATE_VERIFY_FAILED'解决办法
    Centos yum命令
  • 原文地址:https://www.cnblogs.com/KOKODA/p/10631865.html
Copyright © 2011-2022 走看看