Last active
December 18, 2015 07:29
-
-
Save boronology/5746648 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <cmath> | |
| template<typename T> struct complex | |
| { | |
| T real,imag; | |
| complex(T arg1,T arg2) : real(arg1),imag(arg2) | |
| { | |
| } | |
| complex(T arg) : real(arg),imag(0) | |
| { | |
| } | |
| template<typename N=double> N abs() const | |
| { | |
| return std::sqrt(std::pow(this->real,2) + std::pow(this->imag,2)); | |
| } | |
| bool operator==(complex<T> arg) const | |
| { | |
| return this->real==arg.real and this->imag==arg.imag; | |
| } | |
| complex<T> conj() const | |
| { | |
| return complex(this->real, this->imag * -1); | |
| } | |
| complex<T> operator+(const complex a) const | |
| { | |
| return complex(this->real + a.real,this->imag + a.imag); | |
| } | |
| complex<T> operator-(const complex a) const | |
| { | |
| return complex(this->real - a.real,this->imag + a.imag); | |
| } | |
| complex<T> operator*(const complex a) const | |
| { | |
| return complex(this->real * a.real + this->imag * a.imag , | |
| this->imag * a.real + this->real * a.imag); | |
| } | |
| complex<T> operator/(const complex a) const | |
| { | |
| return complex((this->real * a.real + this->imag * a.imag) | |
| / (std::pow(a.real,2) + std::pow(a.imag,2)), | |
| (this->imag * a.real + this->real * a.imag) | |
| / (std::pow(a.real,2) + std::pow(a.imag,2))); | |
| } | |
| } | |
| ; | |
| template<typename T> | |
| std::ostream& operator<<(std::ostream& os, const complex<T>& c) | |
| { | |
| return (c.imag==0)? (os << c.real): | |
| (c.imag<0)? (os << c.real << c.imag << 'i') : | |
| (os << c.real << '+' << c.imag << 'i'); | |
| } | |
| int main() | |
| { | |
| auto hoge = complex<double>(3,4); | |
| std::cout << hoge << std::endl; | |
| std::cout << hoge.abs() << std::endl; | |
| std::cout << hoge * 2 << std::endl; | |
| std::cout << hoge - 3 << std::endl; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment