이번 글에서는 C++에서 복소수(Complex Number)를 생성하고 활용하는 방법을 알아보겠습니다. C++은 객체지향 언어이므로 복소수를 하나의 클래스로 정의할 수 있습니다. 복소수는 실수부(real part)와 허수부(imaginary part)로 구성되므로, 이 두 값을 멤버 변수로 가지는 클래스를 만들고, 복소수 연산을 처리하는 멤버 함수들을 함께 구현하면 됩니다.
복소수 클래스의 기본 구조
아래 예제에서는 다음과 같은 요소들을 포함하는 복소수 클래스를 만들어 보겠습니다.
- 기본 생성자: 복소수를 0+0i로 초기화
- 매개변수 생성자: 실수부와 허수부를 직접 지정하여 초기화
- display() 함수: 허수부의 부호에 따라 복소수를 올바른 형식으로 출력
- add(), sub() 함수: 두 복소수의 덧셈과 뺄셈을 수행하는 friend 함수
덧셈과 뺄셈 함수는 클래스 외부에서 두 객체를 동시에 접근해야 하므로 friend로 선언하여 private 멤버에 자유롭게 접근할 수 있도록 했습니다. 복소수의 덧셈과 뺄셈은 실수부끼리, 허수부끼리 각각 계산하면 됩니다.
예제 코드
#include<iostream>
using namespace std;
class complex{
int real, img;
public:
complex(){
//복소수를 0+0i로 초기화하는 기본 생성자
real = 0; img = 0;
}
complex(int r, int 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;//뺄셈 결과 반환
}
main(){
complex n1(3, 2), n2(4, -3);
complex result;
result = add(n1,n2);
result.display();
result = sub(n1,n2);
result.display();
}실행 결과
The complex number is: 7-i The complex number is: -1 + 5i
코드 해설
예제에서는 실수부가 3이고 허수부가 2인 복소수 n1(3+2i)과, 실수부가 4이고 허수부가 -3인 복소수 n2(4-3i)를 생성했습니다.
- 덧셈: (3+2i) + (4-3i) = (3+4) + (2-3)i = 7-i
- 뺄셈: (3+2i) - (4-3i) = (3-4) + (2+3)i = -1+5i
display() 함수는 허수부 값에 따라 출력 형식을 세분화합니다. 허수부가 -1이면 '-i'만, 1이면 '+ i'만 출력하고, 그 외의 경우에는 부호와 함께 숫자를 표시합니다. 이렇게 하면 '7+-1i'처럼 어색한 형식의 출력을 방지할 수 있습니다.
참고: std::complex 라이브러리 활용
직접 클래스를 구현하지 않고도 C++ 표준 라이브러리의 <complex> 헤더에 포함된 std::complex 템플릿 클래스를 사용하면 복소수를 더욱 편리하게 다룰 수 있습니다. 사칙연산, 켤레복소수(conj), 크기(abs), 편각(arg) 등 다양한 연산이 이미 구현되어 있어 실무에서는 이를 활용하는 것이 좋습니다. 다만, 위 예제처럼 직접 구현해 보면 연산자 오버로딩, friend 함수, 생성자 등 C++의 핵심 개념을 학습하는 데 큰 도움이 됩니다.