챕터 1: C++의 시작과 C와의 차이점 이해 - C 개발자를 위한 C++ 전환 가이드
C 언어의 기초를 다진 개발자라면 C++로의 전환은 자연스러운 다음 단계입니다. 하지만 단순히 C에 클래스만 추가된 것이 아닌, C++만의 독특하고 강력한 기능들을 이해하는 것이 성공적인 전환의 핵심입니다.
학습 목표
이 챕터를 완료하면 다음을 달성할 수 있습니다:
- C와 C++의 근본적인 차이점 이해
- C++ 고유 기능들의 실무적 활용법 습득
- 기존 C 코드를 C++ 스타일로 리팩토링하는 능력 개발
1. namespace와 using: 이름 충돌의 우아한 해결책
C에서 대규모 프로젝트를 진행하다 보면 함수명이나 변수명 충돌로 고생한 경험이 있을 것입니다. C++의 namespace는 이 문제를 근본적으로 해결합니다.
// math_utils.h
namespace MathUtils {
double calculate(double a, double b);
const double PI = 3.14159;
}
// graphics_utils.h
namespace GraphicsUtils {
void calculate(int x, int y); // 같은 이름이지만 충돌하지 않음
}
// main.cpp
using namespace MathUtils; // 전체 namespace 사용
using GraphicsUtils::calculate; // 특정 함수만 사용
int main() {
double result = calculate(3.0, 4.0); // MathUtils::calculate
calculate(10, 20); // GraphicsUtils::calculate
}
실무 팁: using namespace std;는 편리하지만 대규모 프로젝트에서는 피하세요. 대신 using std::cout;처럼 필요한 것만 선택적으로 사용하는 것이 좋습니다.
2. 함수 오버로딩: 하나의 이름, 여러 가지 기능
C에서는 printf_int(), printf_double() 같은 식으로 함수명을 달리해야 했지만, C++에서는 매개변수 타입에 따라 같은 이름의 함수를 여러 개 정의할 수 있습니다.
#include <iostream>
void print(int value) {
std::cout << "정수: " << value << std::endl;
}
void print(double value) {
std::cout << "실수: " << value << std::endl;
}
void print(const std::string& value) {
std::cout << "문자열: " << value << std::endl;
}
// 디폴트 인자 활용
void print(int value, bool newline = true) {
std::cout << "정수: " << value;
if (newline) std::cout << std::endl;
}
3. 참조(Reference): 포인터보다 안전한 별칭
포인터의 복잡함과 위험성을 줄이면서도 효율성을 유지하는 C++의 혁신적 기능입니다.
// C 스타일
void swap_c(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// C++ 스타일
void swap_cpp(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 10, y = 20;
// C 스타일 호출
swap_c(&x, &y);
// C++ 스타일 호출 (더 직관적)
swap_cpp(x, y);
}
참조의 장점:
- NULL이 될 수 없어 안전함
- 초기화 시점에 반드시 유효한 객체와 연결
- 포인터 산술 연산 불가로 메모리 오류 방지
4. new/delete: 타입 안전한 동적 메모리 관리
// C 스타일
int* arr_c = (int*)malloc(sizeof(int) * 10);
free(arr_c);
// C++ 스타일
int* arr_cpp = new int[10];
delete[] arr_cpp;
// 더 나은 C++ 스타일 (생성자 호출)
std::string* str = new std::string("Hello World");
delete str;
중요: 나중에 스마트 포인터를 배우면 new/delete를 직접 사용할 일이 거의 없어집니다.
5. bool 타입과 auto: 타입 안정성과 편의성
// bool 타입으로 의도 명확화
bool isValid = true;
bool hasData = (data != nullptr);
// auto로 타입 추론 (C++11부터)
auto number = 42; // int
auto price = 99.99; // double
auto name = "John"; // const char*
auto text = std::string("Hello"); // std::string
6. 범위 기반 for 루프: 간결한 반복문
#include <vector>
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 전통적인 방법
for (size_t i = 0; i < numbers.size(); ++i) {
std::cout << numbers[i] << " ";
}
// 범위 기반 for 루프
for (int num : numbers) {
std::cout << num << " ";
}
// 참조로 받아서 수정 가능
for (int& num : numbers) {
num *= 2;
}
실습 프로젝트: 학생 성적 관리 시스템 리팩토링
C 스타일에서 C++ 스타일로 전환하는 과정을 직접 경험해보겠습니다.
C 스타일 (기존 코드)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[50];
int score;
} Student;
void print_student(Student* s) {
printf("이름: %s, 점수: %d\n", s->name, s->score);
}
int main() {
Student* students = malloc(sizeof(Student) * 3);
strcpy(students[0].name, "김철수");
students[0].score = 85;
for (int i = 0; i < 3; i++) {
print_student(&students[i]);
}
free(students);
return 0;
}
C++ 스타일 (리팩토링 후)
#include <iostream>
#include <string>
#include <vector>
class Student {
private:
std::string name;
int score;
public:
Student(const std::string& n = "", int s = 0) : name(n), score(s) {}
void print() const {
std::cout << "이름: " << name << ", 점수: " << score << std::endl;
}
// 참조로 안전하게 데이터 접근
const std::string& getName() const { return name; }
int getScore() const { return score; }
};
int main() {
std::vector<Student> students = {
Student("김철수", 85),
Student("이영희", 92),
Student("박민수", 78)
};
// 범위 기반 for 루프 사용
for (const auto& student : students) {
student.print();
}
return 0;
}
추천 학습 자료
필수 도서
- "C++ Primer (5th Edition)" - Stanley Lippman: 가장 권위 있는 C++ 입문서
- "전문가를 위한 C++" - 한국어로 된 실무 중심의 설명
무료 온라인 영상 강의
- 한국어 강의
- 홍정모의 따라하며 배우는 C++ (YouTube): 기초부터 체계적으로 설명
- 나도코딩 C++ 강의: 입문자 친화적인 설명
- 영어 강의(유튜브 추천, why? 자동번역되어서)
- The Cherno C++ Series (YouTube): 실무 개발자의 실전 중심 강의
- CodeBeauty C++ Tutorial: 초보자도 이해하기 쉬운 설명
- Programming with Mosh - C++ Tutorial: 간결하고 명확한 설명
실습 환경 구축
- 온라인: Compiler Explorer (godbolt.org), repl.it
- 로컬: Visual Studio Code + C++ Extension, CLion, Visual Studio
참고 사이트
- cppreference.com: C++ 공식 레퍼런스
- LearnCpp.com: 체계적인 온라인 튜토리얼
- isocpp.org: C++ 표준 위원회 공식 사이트
'C++' 카테고리의 다른 글
| C++ 한달 완성 프로젝트 및 커리큘럼 (0) | 2025.09.25 |
|---|
