C++ 연산자 오버로딩 | '+, -, *, <<' 재정의 가이드
이 글의 핵심
class Complex { private: double real, imag; public: Complex(double r = 0, double i = 0) : real(r), imag(i) {}.
기본 산술 연산자
class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// + 연산자
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// - 연산자
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}
void print() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 4);
Complex c2(1, 2);
Complex c3 = c1 + c2; // operator+ 호출
c3.print(); // 4 + 6i
}
비교 연산자
class Point {
public:
int x, y;
Point(int x, int y) : x(x), y(y) {}
bool operator==(const Point& other) const {
return x == other.x && y == other.y;
}
bool operator!=(const Point& other) const {
return !(*this == other);
}
bool operator<(const Point& other) const {
if (x != other.x) return x < other.x;
return y < other.y;
}
};
int main() {
Point p1(1, 2);
Point p2(1, 2);
Point p3(2, 3);
cout << (p1 == p2) << endl; // 1 (true)
cout << (p1 < p3) << endl; // 1 (true)
}
입출력 연산자 (friend)
class Vector2D {
private:
double x, y;
public:
Vector2D(double x = 0, double y = 0) : x(x), y(y) {}
// << 연산자 (friend 필요)
friend ostream& operator<<(ostream& os, const Vector2D& v) {
os << "(" << v.x << ", " << v.y << ")";
return os;
}
// >> 연산자
friend istream& operator>>(istream& is, Vector2D& v) {
is >> v.x >> v.y;
return is;
}
};
int main() {
Vector2D v(3.5, 4.2);
cout << v << endl; // (3.5, 4.2)
Vector2D v2;
cin >> v2; // 입력: 1 2
cout << v2 << endl; // (1, 2)
}
실전 예시
예시 1: 분수 클래스
#include <iostream>
#include <numeric>
using namespace std;
class Fraction {
private:
int numerator; // 분자
int denominator; // 분모
void simplify() {
int gcd = std::gcd(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
}
public:
Fraction(int n = 0, int d = 1) : numerator(n), denominator(d) {
if (d == 0) throw invalid_argument("분모는 0이 될 수 없습니다");
simplify();
}
Fraction operator+(const Fraction& other) const {
return Fraction(
numerator * other.denominator + other.numerator * denominator,
denominator * other.denominator
);
}
Fraction operator-(const Fraction& other) const {
return Fraction(
numerator * other.denominator - other.numerator * denominator,
denominator * other.denominator
);
}
Fraction operator*(const Fraction& other) const {
return Fraction(
numerator * other.numerator,
denominator * other.denominator
);
}
Fraction operator/(const Fraction& other) const {
return Fraction(
numerator * other.denominator,
denominator * other.numerator
);
}
bool operator==(const Fraction& other) const {
return numerator == other.numerator && denominator == other.denominator;
}
friend ostream& operator<<(ostream& os, const Fraction& f) {
if (f.denominator == 1) {
os << f.numerator;
} else {
os << f.numerator << "/" << f.denominator;
}
return os;
}
};
int main() {
Fraction f1(1, 2); // 1/2
Fraction f2(1, 3); // 1/3
cout << f1 << " + " << f2 << " = " << (f1 + f2) << endl; // 5/6
cout << f1 << " * " << f2 << " = " << (f1 * f2) << endl; // 1/6
return 0;
}
설명: 연산자 오버로딩으로 분수 연산을 직관적으로 표현할 수 있습니다.
예시 2: 행렬 클래스
#include <iostream>
#include <vector>
using namespace std;
class Matrix {
private:
vector<vector<int>> data;
int rows, cols;
public:
Matrix(int r, int c) : rows(r), cols(c) {
data.resize(r, vector<int>(c, 0));
}
int& operator()(int r, int c) {
return data[r][c];
}
Matrix operator+(const Matrix& other) const {
if (rows != other.rows || cols != other.cols) {
throw invalid_argument("행렬 크기가 다릅니다");
}
Matrix result(rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.data[i][j] = data[i][j] + other.data[i][j];
}
}
return result;
}
Matrix operator*(const Matrix& other) const {
if (cols != other.rows) {
throw invalid_argument("행렬 곱셈 불가");
}
Matrix result(rows, other.cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < other.cols; j++) {
for (int k = 0; k < cols; k++) {
result.data[i][j] += data[i][k] * other.data[k][j];
}
}
}
return result;
}
friend ostream& operator<<(ostream& os, const Matrix& m) {
for (int i = 0; i < m.rows; i++) {
for (int j = 0; j < m.cols; j++) {
os << m.data[i][j] << " ";
}
os << endl;
}
return os;
}
};
int main() {
Matrix m1(2, 2);
m1(0, 0) = 1; m1(0, 1) = 2;
m1(1, 0) = 3; m1(1, 1) = 4;
Matrix m2(2, 2);
m2(0, 0) = 5; m2(0, 1) = 6;
m2(1, 0) = 7; m2(1, 1) = 8;
cout << "m1 + m2:" << endl << (m1 + m2) << endl;
cout << "m1 * m2:" << endl << (m1 * m2) << endl;
return 0;
}
설명: () 연산자로 행렬 원소 접근을 직관적으로 만들고, +와 * 연산자로 행렬 연산을 구현합니다.
예시 3: 스마트 문자열 클래스
#include <iostream>
#include <cstring>
using namespace std;
class String {
private:
char* data;
size_t length;
public:
String(const char* str = "") {
length = strlen(str);
data = new char[length + 1];
strcpy(data, str);
}
~String() {
delete[] data;
}
// 복사 생성자
String(const String& other) {
length = other.length;
data = new char[length + 1];
strcpy(data, other.data);
}
// 대입 연산자
String& operator=(const String& other) {
if (this != &other) {
delete[] data;
length = other.length;
data = new char[length + 1];
strcpy(data, other.data);
}
return *this;
}
// + 연산자 (문자열 연결)
String operator+(const String& other) const {
char* temp = new char[length + other.length + 1];
strcpy(temp, data);
strcat(temp, other.data);
String result(temp);
delete[] temp;
return result;
}
// [] 연산자
char& operator {
return data[index];
}
// == 연산자
bool operator==(const String& other) const {
return strcmp(data, other.data) == 0;
}
friend ostream& operator<<(ostream& os, const String& str) {
os << str.data;
return os;
}
};
int main() {
String s1("Hello");
String s2(" World");
String s3 = s1 + s2;
cout << s3 << endl; // Hello World
cout << s3[0] << endl; // H
return 0;
}
설명: 문자열 클래스에 연산자 오버로딩을 적용하여 사용성을 높입니다.
자주 발생하는 문제
문제 1: 대입 연산자에서 자기 대입 체크 누락
증상: 자기 자신을 대입하면 크래시
원인: delete 후 복사 시도
해결법:
// ❌ 위험한 코드
String& operator=(const String& other) {
delete[] data; // 자기 자신이면 문제!
data = new char[other.length + 1];
strcpy(data, other.data);
return *this;
}
// ✅ 자기 대입 체크
String& operator=(const String& other) {
if (this != &other) { // 자기 대입 체크
delete[] data;
data = new char[other.length + 1];
strcpy(data, other.data);
}
return *this;
}
문제 2: const 정확성
증상: const 객체에서 연산자 호출 불가
원인: const 키워드 누락
해결법:
C/C++ 예제 코드입니다.
// ❌ const 객체에서 호출 불가
Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
// ✅ const 멤버 함수
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
문제 3: 연산자 우선순위 무시
증상: 예상과 다른 결과
원인: 연산자 우선순위 오해
해결법:
// 연산자 우선순위는 변경 불가
// 괄호로 명확하게 표현
Complex c = (a + b) * c; // 명확
FAQ
Q1: 모든 연산자를 오버로딩할 수 있나요?
A: 아니요, 일부는 불가능합니다.
- 오버로딩 불가:
::,.,.*,?:,sizeof - 오버로딩 가능:
+,-,*,/,==,<<,[]등
Q2: friend는 왜 필요한가요?
A: <<, >> 같은 연산자는 왼쪽 피연산자가 ostream/istream이므로 멤버 함수로 만들 수 없습니다.
Q3: 연산자 오버로딩은 언제 사용하나요?
A:
- 수학적 객체 (벡터, 행렬, 복소수)
- 컨테이너 (배열, 리스트)
- 스마트 포인터
Q4: 성능에 영향이 있나요?
A: 인라인화되면 오버헤드가 거의 없습니다. 컴파일러가 최적화합니다.
Q5: ++a vs a++는 어떻게 구현하나요?
A:
C/C++ 예제 코드입니다.
// 전위 증가
T& operator++() {
// 증가
return *this;
}
// 후위 증가 (int는 더미 매개변수)
T operator++(int) {
T temp = *this;
++(*this);
return temp;
}
Q6: 연산자 오버로딩 남용은?
A: 직관적이지 않은 연산자 오버로딩은 피하세요. 예: +를 파일 삭제에 사용하는 것은 나쁜 예입니다.
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ 연산자 우선순위 | “Operator Precedence” 가이드
- C++ ADL | “Argument Dependent Lookup” 가이드
- C++ User-Defined Literals | “사용자 정의 리터럴” 가이드
관련 글
심화 부록: 구현·운영 관점
이 부록은 본문 주제 「C++ 연산자 오버로딩 | ’+, -, *, <<’ 재정의 가이드」을 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.
내부 동작과 핵심 메커니즘
flowchart TD A[입력·요청·이벤트] --> B[파싱·검증·디코딩] B --> C[핵심 연산·상태 전이] C --> D[부작용: I/O·네트워크·동시성] D --> E[결과·관측·저장]
sequenceDiagram participant C as 클라이언트/호출자 participant B as 경계(런타임·게이트웨이·프로세스) participant D as 의존성(API·DB·큐·파일) C->>B: 요청/이벤트 B->>D: 조회·쓰기·RPC D-->>B: 지연·부분 실패·재시도 가능 B-->>C: 응답 또는 오류(코드·상관 ID)
- 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
- 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
- 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
- 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.
프로덕션 운영 패턴
| 영역 | 운영 관점 질문 |
|---|---|
| 관측성 | 요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가 |
| 안전성 | 입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가 |
| 신뢰성 | 재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가 |
| 성능 | 캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가 |
| 배포 | 롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가 |
| 용량 | 피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가 |
스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.
확장 예시: 엔드투엔드 미니 시나리오
「C++ 연산자 오버로딩 | ’+, -, *, <<’ 재정의 가이드」을 배포·운영 흐름으로 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.
- 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
- 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
- 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
- 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
- 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
ctx = newCorrelationId()
validated = validateSchema(request)
authorize(validated, ctx)
result = domainCore(validated)
persistOrEmit(result, idempotentKey)
recordMetrics(ctx, latency, outcome)
return result
문제 해결(Troubleshooting)
| 증상 | 가능 원인 | 조치 |
|---|---|---|
| 간헐적 실패 | 레이스, 타임아웃, 외부 의존성, DNS | 최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검 |
| 성능 저하 | N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스 | 프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거 |
| 메모리 증가 | 캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납 | 상한·TTL·힙/FD 스냅샷 비교 |
| 빌드·배포만 실패 | 환경 변수, 권한, 플랫폼 차이, lockfile | CI 로그와 로컬 diff, 런타임·이미지 버전 핀 |
| 설정 불일치 | 프로필·시크릿·기본값, 리전 | 스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화 |
| 데이터 불일치 | 비멱등 재시도, 부분 쓰기, 캐시 무효화 누락 | 멱등 키·아웃박스·트랜잭션 경계 재검토 |
권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.
배포 전에는 git add → git commit → git push 후 npm run deploy 순서를 권장합니다.
이 글에서 다루는 키워드 (관련 검색어)
C++, 연산자오버로딩, operator, 연산자 등으로 검색하시면 이 글이 도움이 됩니다.