CPP 연산자 오버로딩

Programming/C,CPP,CS 2014. 1. 16. 12:42 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

#include <iostream>

#include <string>

using namespace std;


class ImaginaryNumber

{

public:

ImaginaryNumber();

ImaginaryNumber(double a, double b);

void SetA(double a);

void SetB(double b);

double GetA();

double GetB();

char* GetImaginaryNumber();

ImaginaryNumber addImaginaryNumber(ImaginaryNumber in2);

ImaginaryNumber operator+(ImaginaryNumber in2);


private:

double a; //실수부

double b; //허수부 (b≠0)

};


ImaginaryNumber::ImaginaryNumber()

{

a = 0;

b = 0;

}

ImaginaryNumber::ImaginaryNumber(double a, double b)

{

this->a = a;

this->b = b;

}

void ImaginaryNumber::SetA(double a)

{

this->a = a;

}

void ImaginaryNumber::SetB(double b)

{

this->b = b;

}

double ImaginaryNumber::GetA()

{

return a;

}

double ImaginaryNumber::GetB()

{

return b;

}


char* ImaginaryNumber::GetImaginaryNumber()

{

static char text[30];

sprintf(text, "%lf %+lf i", a, b);

return text;

}


ImaginaryNumber ImaginaryNumber::addImaginaryNumber(ImaginaryNumber in2)

{

ImaginaryNumber result;

result.a = a + in2.a;

result.b = b + in2.b;

return result;

}


ImaginaryNumber ImaginaryNumber::operator+(ImaginaryNumber in2)

{

ImaginaryNumber result;

result.a = a + in2.a;

result.b = b + in2.b;

return result;

}

int main ()

{

ImaginaryNumber in1( 3 , -4 ); // 3 -4i

ImaginaryNumber in2( 5 , -2 ); // 5 -2i

cout << in1.GetImaginaryNumber() << endl;

cout << in2.GetImaginaryNumber() << endl;

ImaginaryNumber in4 = in1 + in2;


cout << in4.GetImaginaryNumber() << endl;


return 0;

}