/* myComplex.h */
class myComplex{
private:
double x; /* real part */
double y; /* imaginary part */
public:
myComplex(double xx=0, double yy=0){ x = xx; y=yy; }
void setReal(double xx){ x = xx; }
void setImag(double yy){ y = yy; }
double getReal(void){ return x; }
double getImag(void){ return y; }
double norm(void);
myComplex operator+(const myComplex& c){
return( myComplex(x+c.x, y+c.y) );
}
myComplex operator-(const myComplex& c){
return( myComplex(x-c.x, y-c.y) );
}
myComplex operator*(const myComplex& c){
return( myComplex(x*c.x-y*c.y, x*c.y+y*c.x) );
}
};
/* myComplex.cpp */
#include <math.h>
#include "myComplex.h"
double myComplex::norm(void){
return(sqrt(x*x + y*y));
}
/* complex_test.cpp */
#include <iostream>
#include "myComplex.h"
using namespace std;
int main(void){
myComplex c1(3,4); /* myComplex 型の変数 */
myComplex c2(1,1);
myComplex c3;
myComplex *cp1, *cp2, *cp3; /* myComplex 型のポインタ */
cp1 = new myComplex; /* ヒープ領域への確保 */
cp2 = new myComplex(5);
cp3 = new myComplex(3,4);
c3 = c1 + c2; /* 加算 */
cout << "c1+c2=" << c3.getReal() << "+" << c3.getImag() << "i" << endl;
c3 = c1 - c2; /* 減算 */
cout << "c1-c2=" << c3.getReal() << "+" << c3.getImag() << "i" << endl;
c3 = c1 * c2; /* 乗算 */
cout << "c1*c2=" << c3.getReal() << "+" << c3.getImag() << "i" << endl;
delete cp1; /* 領域の開放 */
delete cp2;
delete cp3;
return 0;
}
|