썸네일

C++ 언어 소개와 기초 문법 정리

C++는 성능 중심의 범용 프로그래밍 언어로, C 언어를 기반으로 객체지향 기능이 추가된 구조를 가지고 있다.
이번 글에서는 C++ 개발자 로드맵의 첫 번째 단원인 Introduction of Language를 바탕으로, 기본적인 문법을 간단한 예제들과 함께 정리한다.


1. C++ 기본 구조

C++ 프로그램의 시작점은 main() 함수이며, 표준 라이브러리(iostream)를 포함하는 것으로 시작한다.

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

2. 입출력

C++에서는 std::cout으로 출력하고, std::cin으로 입력을 받는다.

#include <iostream>

int main() {
    int number;
    std::cout << "정수를 입력하세요: ";
    std::cin >> number;
    std::cout << "입력한 값은: " << number << std::endl;
    return 0;
}

3. 변수와 데이터 타입

C++에서 사용되는 기본적인 데이터 타입은 다음과 같다.

int age = 25;
float height = 175.5f;
double weight = 68.2;
char grade = 'A';
bool isPassed = true;

출력 예시

std::cout << std::boolalpha << isPassed << std::endl; // true

4. 조건문과 반복문

if-else

if (score >= 90) {
    std::cout << "A";
} else if (score >= 80) {
    std::cout << "B";
} else {
    std::cout << "F";
}

while

while (number != 0) {
    sum += number;
    std::cin >> number;
}

for

for (int i = 1; i <= 10; i++) {
    sum += i;
}

switch

switch (day) {
    case 1:
        std::cout << "일요일";
        break;
    default:
        std::cout << "유효하지 않음";
}

5. 함수 정의와 호출

int add(int a, int b) {
    return a + b;
}

int main() {
    std::cout << add(3, 4); // 7
}

6. 클래스와 객체

C++의 핵심은 객체지향이다. 클래스는 상태와 동작을 하나로 묶는다.

class Calculator {
public:
    int multiply(int a, int b) {
        return a * b;
    }
};

int main() {
    Calculator calc;
    std::cout << calc.multiply(3, 4); // 12
}

7. C와 C++ 비교

C

  • 패러다임 : 절차지향
  • 구조 : 함수 중심
  • 입출력 : printf/scanf
  • 에러 처리 : 반환값 처리
#include <stdio.h>

void printHello() {
    printf("Hello, World!\n");
}

int main() {
    printHello();
}

C++

  • 패러다임 : 객체지향 지원
  • 구조 : 클래스 중심
  • 입출력 : cout/cin
  • 에러 처리 : 예외 처리
#include <iostream>

class HelloWorld {
public:
    void printHello() {
        std::cout << "Hello, World!\n";
    }
};

int main() {
    HelloWorld obj;
    obj.printHello();
}

마무리

C++은 높은 성능과 다양한 프로그래밍 패러다임을 지원하는 강력한 언어다.
이번 단원에서는 가장 기초적인 문법을 다루었지만, 이 토대 위에 포인터, 클래스 설계, 템플릿, STL 등 심화 내용을 쌓아나가야 한다.

코드 예제는 모두 아래 GitHub 저장소에 정리되어 있다:

👉 예제 코드 보러 가기

다음 글에서는 C++ 개발을 위한 환경 설정 방법(Setting Up Your Environment)에 대해 정리할 예정이다.
컴파일러 설치부터 편집기 추천, 빌드 및 실행 방법까지 함께 살펴보자.

👉 티스토리 요약 보러 가기

profile
Server Dev

0개의 댓글