C++ 클래스와 객체: 객체지향 프로그래밍 실전 가이드
C++ 클래스와 객체
데이터와 행동을 캡슐화하는 C++ 클래스와 객체의 핵심 개념을 명확한 예제와 모범 사례와 함께 익혀보세요.
왜 클래스를 사용하나요?
앞서 함수와 변수를 배웠습니다. 프로젝트가 커지면 관련 데이터와 연산을 묶는 게 유지보수성과 명확성에 필수적입니다. 클래스는 데이터 멤버와 멤버 함수를 하나의 논리적 단위로 묶어 **객체지향 프로그래밍(OOP)**—현대 C++ 설계의 기초—를 가능하게 합니다.
예시: 방(Room)
직사각형 방이 있습니다. 길이, 너비, 높이를 저장하면서 면적과 부피 계산도 필요합니다. 클래스로 이들을 긴밀히 결합:
class Room {
public:
double length;
double breadth;
double height;
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
클래스 정의
class 키워드로 정의, 이름 뒤에 중괄호로 본문 감싸고 세미콜론으로 끝:
class ClassName {
// 데이터 멤버
// 멤버 함수
};
위 예에서 Room은 **청사진(Blueprint)**입니다. 내부의 변수들은 **데이터 멤버**, 함수들은 **멤버 함수**라 부릅니다.
객체 생성
클래스 정의만으로는 메모리 할당 안 됨. 청사진으로부터 **구체적 인스턴스**인 객체 생성:
Room room1; // 단일 객체
Room room2, room3; // 한 선언에 여러 객체
객체는 함수 안, 다른 클래스 안, 전역 등 스코프만 존중하면 어디서든 인스턴스화 가능.
멤버 접근
멤버 함수 호출이나 데이터 멤버 접근엔 도트(.) 연산자 사용:
room1.length = 5.5;
double area = room1.calculateArea();
예제 1: 방의 면적과 부피 계산
#include <iostream>
using namespace std;
class Room {
public:
double length;
double breadth;
double height;
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
Room room1;
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;
return 0;
}
실행 결과
Area of Room = 1309
Volume of Room = 25132.8
캡슐화: Public vs Private
캡슐화는 접근 제어로 데이터를 보호합니다. private 멤버는 외부에서 숨겨지고 public 멤버 함수를 통해서만 접근 가능.
class Test {
private:
int a;
void function1() {}
public:
int b;
void function2() {}
};
다음 예제에서 데이터 멤버는 private이고 public 메서드로 초기화:
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
void initData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
Room room1;
room1.initData(42.5, 30.8, 19.2);
cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;
return 0;
}
실행 결과
Area of Room = 1309
Volume of Room = 25132.8
더 알아보기
권위 있는 지침은 ISO/IEC 14882:2023 C++ 표준이나 cplusplus.com, cppreference.com 같은 신뢰할 수 있는 자료를 참조하세요.