#include <iostream>
class Complex
{
private:
double real, img;
public:
Complex(double real, double img) : real(real), img(img) {}
Complex(const Complex& c)
{
real = c.real;
img = c.img;
}
Complex operator+(const Complex& c) const;
Complex operator-(const Complex& c) const;
Complex operator*(const Complex& c) const;
Complex operator/(const Complex& c) const;
void println()
{
std::cout << "(" << real << " , " << img << " ) " << std::endl;
}
};
// +
Complex Complex::operator+(const Complex& c) const
{
Complex temp(real + c.real, img + c.img);
return temp;
}
// -
Complex Complex::operator-(const Complex& c) const
{
Complex temp(real - c.real, img - c.img);
return temp;
}
// *
Complex Complex::operator*(const Complex& c) const
{
Complex temp(real * c.real - img * c.img, real * c.img + img * c.real);
return temp;
}
// /
Complex Complex::operator/(const Complex& c) const
{
Complex temp(
(real * c.real + img * c.img) / (c.real * c.real + c.img * c.img),
(img * c.real - real * c.img) / (c.real * c.real + c.img * c.img)
);
return temp;
}
int main()
{
Complex a(1.0, 2.0);
Complex b(3.0, -2.0);
Complex c = a * b;
c.println();
}
실행결과
( 7, 4 )
해당 클래스에서는 산술연산자 오버로딩 시 Complex를 return 하고있는데
사칙연산의 경우 Complex&를 리턴할 경우 의도한 바와 다르게 계산될 여지가 있기 때문에 반드시
값을 리턴해줘야한다.
기본적으로 대입연산자 함수는 연칙연산자 함수와 다르게 레퍼런스를 리턴한다.
대입 연산자가 레퍼런스를 리턴해야 되는 이유는
a = b = c;
위와 같은 코드에서 b = c;가 b를 리턴해야만 a = b 를 수행할 수 있고 대입 연산 이후 불필요한 복사를 방지하기 위함이다.
...(생략)
Complex& Complex::operator=(const Complex& c)
{
real = c.real;
img = c.img;
return *this;
}
int main()
{
Complex a(1.0, 2.0);
Complex b(3.0, -2.0);
Complex c(0.0, 0.0);
c = a * b + a / b + a + b;
c.println();
}
실행결과
( 10.9231 , 4.61538 )
Complex& Complex::operator+=(const Complex& c)
{
(*this) = (*this) + c;
return *this;
}
Complex& Complex::operator-=(const Complex& c)
{
(*this) = (*this) - c;
return *this;
}
Complex& Complex::operator*=(const Complex& c)
{
(*this) = (*this) * c;
return *this;
}
Complex& Complex::operator/=(const Complex& c)
{
(*this) = (*this) / c;
return *this;
}
int main() {
Complex a(1.0, 2.0);
Complex b(3.0, -2.0);
a += b;
a.println();
b.println();
}
실행결과
( 4 , 0 )
( 3 , -2 )
대입 사칙연산자는 일반 사칙연산자와는 다르게 객체 내부의 상태를 변경하기 때문에 const로 선언하면 안된다.
연산자 오버로딩 시
a = a + b;
!=
a += b;
+=를 반드시 정의해줘야함!