복소수는 사칙연산이 많이 일어난다. 이 사칙연산을 일반적인 메서드(plus()와 같은 형태)로 나타낸다면 복잡한 사칙연산의 식에서 가독성이 크게 떨어지게 된다. 이런 경우에 대비하기 위하여 연산자 오버로딩을 적극 활용하여 클래스를 구성한다.

<aside> 💡 연산자 오버로딩 활용

</aside>

$$ a = b + c + b $$

사칙연산 연산자 오버로딩에 경우에는 일반적으로 값을 리턴해줘야한다. 만약 위와 같은 식이 있을경우, 사용자는 a= 2b+c를 예상하고 작성할수도 있지만, 만약 연산자 오버로딩의 결과를 레퍼런스로 반환해주게되면 b+c 연산 후 b에는 b+c가 들어가버리기 때문에 결과적으로는 **a=2(b+c)**와 같은 값이 나오게 된다. 이러한 결과를 의도하는게 아니라면 사칙연산 연산자 오버로딩의 결과값은 레퍼런스나 포인터가 아닌 값을 리턴해줘야 한다. 또한 인자값이 바뀌지 않는것이 확실한 경우에는 const 키워드를 붙여주는게 좋다.

사칙연산과 대입 연산자 오버로딩이 적용된 소스

#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);
	Complex operator-(const Complex& c);
	Complex operator*(const Complex& c);
	Complex operator/(const Complex& c);
	Complex& operator=(const Complex& c);
	void println() {
		std::cout << "( " << real << " , " << img << " ) " << std::endl;
	}
};

Complex Complex::operator+(const Complex& c) {
	Complex temp(real + c.real, img + c.img);
	return temp;
}

Complex Complex::operator-(const Complex& c) {
	Complex temp(real - c.real, img - c.img);
	return temp;
}

Complex Complex::operator*(const Complex& c) {
	Complex temp(real * c.real - img * c.img, real * c.img + img * c.real);
	return temp;
}

Complex Complex::operator/(const Complex& c) {
	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;
}

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();
}

사실 대입 연산자도 복사 연산자처럼 디폴트 복사 생성자가 존재한다. 디폴트 복사 연산자도 기본적으로 얕은 복사로 동작하며, 만약 동적으로 메모리를 관리하는 포인터가 있다면 이에 대한 처리를 하기 위해 대입 연산자 함수를 만들어줄 필요가 있다.

<aside> 💡 // 복사 생성자 호출 Some_Class a = b;

//기본생성자 후 대입 연산자 호출 Some_Class = a; a = b

</aside>

문자열로 Complex 수와 덧셈하기

$y = z + "3+i2"$

operator+를 개량해서 위와 같은 문자열로도 덧셈을 할 수 있도록 연산자 오버로딩을 만들어보자.

→ i를 기준으로 실수부와 허수부를 구분. 만약 i가 없다면 실수(real)처리