c_cpp complex.h

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp complex.h相关的知识,希望对你有一定的参考价值。

#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>
#include <cmath>

class Complex {
protected:
  float real;
  float imaginary;
public:
  Complex(float a, float b): real(a), imaginary(b) {}
  Complex(){
    real = 0;
    imaginary=0;
  }
  void setReal(float a);
  void setImaginary(float b);
  float getReal();
  float getImaginary();
  Complex Conjugate();

  friend std::ostream& operator<<(std::ostream& os, Complex i){
    if (std::abs(i.getImaginary())==i.getImaginary()) {
      os << i.getReal() << "+" << i.getImaginary() << "i"  << std::endl;
    } else {
      os << i.getReal() << i.getImaginary() << "i" << std::endl;
    }
    //wtf?!
      //os << i.getReal() << (std::abs(i.getImaginary())==i.getImaginary())?"+":"" << i.getImaginary() << "i" << std::endl;
    return os;
  };
  friend Complex operator+(Complex a, Complex b){
    Complex temp;
    temp.setReal(a.getReal() + b.getReal());
    temp.setImaginary(a.getImaginary() + b.getImaginary());
    return temp;
  };
  friend Complex operator-(Complex a, Complex b){
    Complex temp;
    temp.setReal(a.getReal() - b.getReal());
    temp.setImaginary(a.getImaginary() - b.getImaginary());
    return temp;
  };
  friend Complex operator*(Complex a, Complex b){
    Complex temp;
    temp.setReal(a.getReal() * b.getReal() - a.getImaginary() * b.getImaginary());
    temp.setImaginary(a.getReal() * b.getImaginary() + a.getImaginary() * b.getReal());
    return temp;
  };
  friend Complex operator/(Complex a, float i){
    Complex temp;
    temp.setReal(a.getReal() / i);
    temp.setImaginary(a.getImaginary() / i);
    return temp;
  };
  friend Complex operator/(Complex a, Complex i){
    Complex temp;
    temp = a * i.Conjugate();
    temp = temp / (pow(i.getReal(),2) + pow(i.getImaginary(),2));
    return temp;
  };

};



#endif //COMPLEX_H

以上是关于c_cpp complex.h的主要内容,如果未能解决你的问题,请参考以下文章

Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,<pybind11/functional.h>

gsl 复数

函数模版和主函数分别在.h .cpp中(要包含.cpp)

006.头文件 | 基础知识

第四次实验

cpp 面向对象初步探索