C++에서는 실수부와 허수부를 멤버 변수로 가지는 클래스를 직접 정의해 복소수를 표현할 수 있습니다. 이 글에서는 복소수를 저장하는 클래스를 만들고, 두 복소수의 덧셈과 뺄셈을 처리한 뒤, 결과를 a+bi 형태로 읽기 좋게 출력하는 방법을 단계별로 살펴봅니다.
복소수 클래스의 구성 요소
예제에서 만들 복소수(complex) 클래스는 다음 요소들로 이루어집니다.
- 멤버 변수 – 실수부(real)와 허수부(img)를 저장합니다.
- 기본 생성자 – 복소수를 0+0i로 초기화합니다.
- 매개변수 생성자 – 실수부와 허수부를 인자로 받아 초기화합니다.
- 입력 함수(set) – 사용자로부터 실수부와 허수부를 입력받습니다.
- 출력 함수(get, display) – 허수부의 부호와 크기에 따라 적절한 형식으로 복소수를 출력합니다.
- friend 함수(add, sub) – 클래스의 private 멤버에 접근해 두 복소수의 덧셈과 뺄셈을 수행합니다.
예제 코드
#include<iostream>
using namespace std;
class complex {
int real, img;
public:
complex() {
// 기본 생성자: 복소수를 0+0i로 초기화
real = 0; img = 0;
}
complex(int r, int i) {
// 매개변수 생성자: 실수부 r, 허수부 i로 초기화
real = r; img = i;
}
void set();
void get();
void display();
friend complex add(complex, complex);
friend complex sub(complex, complex);
};
void complex::set() {
cout << "Enter Real part: ";
cin >> real;
cout << "Enter Imaginary Part: ";
cin >> img;
}
void complex::get() {
cout << "The complex number is: " << real << "+" << img << "i" << endl;
}
void complex::display() {
if (img < 0)
if (img == -1)
cout << "The complex number is: " << real << "-i" << endl;
else
cout << "The complex number is: " << real << img << "i" << endl;
else
if (img == 1)
cout << "The complex number is: " << real << " + i" << endl;
else
cout << "The complex number is: " << real << " + " << img << "i" << endl;
}
// 실수부끼리, 허수부끼리 각각 더한다
complex add(complex c1, complex c2) {
complex res;
res.real = c1.real + c2.real;
res.img = c1.img + c2.img;
return res;
}
// 실수부끼리, 허수부끼리 각각 뺀다
complex sub(complex c1, complex c2) {
complex res;
res.real = c1.real - c2.real;
res.img = c1.img - c2.img;
return res;
}
int main() {
complex n1(3, 2), n2(4, -3);
complex result;
result = add(n1, n2); // (3+2i) + (4-3i)
result.display();
result = sub(n1, n2); // (3+2i) - (4-3i)
result.display();
return 0;
}실행 결과
The complex number is: 7-i The complex number is: -1 + 5i
코드 설명
n1은 3+2i, n2는 4-3i로 초기화되며, 각 연산은 다음과 같이 진행됩니다.
- 덧셈: (3+2i) + (4-3i) = (3+4) + (2-3)i = 7-i → 허수부가 -1이므로 "7-i" 형태로 출력됩니다.
- 뺄셈: (3+2i) - (4-3i) = (3-4) + (2+3)i = -1+5i → 허수부가 양수이므로 "-1 + 5i" 형태로 출력됩니다.
display() 함수는 허수부 값에 따라 출력 형식을 조정합니다. 허수부가 -1이면 "-i", 1이면 "+ i"만 출력하고, 그 외의 경우에는 숫자를 함께 표시해 자연스러운 수학 표기를 만듭니다.
참고: 표준 라이브러리의 std::complex
실무에서는 위처럼 클래스를 직접 작성하기보다 <complex> 헤더가 제공하는 std::complex 템플릿을 사용하는 것이 좋습니다. 사칙연산 연산자 오버로딩은 물론 켤레 복소수(conj), 절댓값(abs), 크기 제곱(norm) 등의 기능이 이미 구현되어 있으며, float, double, long double 타입을 지원합니다.
#include <iostream>
#include <complex>
using namespace std;
int main() {
complex<double> n1(3.0, 2.0), n2(4.0, -3.0);
cout << n1 + n2 << endl; // (7,-1)
cout << n1 - n2 << endl; // (-1,5)
return 0;
}