본문 바로가기
Programming/C++

[C++] 4. 클래스와 객체

by Lizardee 2024. 1. 29.
4.1 이번 장에서 만들어 볼 프로그램

4.2 객체 지향이란?
  • 절차 지향 프로그래밍(procedure programming): 프로시저(procedure)를 기반으로 하는 프로그래밍 방법
  • 객체 지향 프로그래밍: 데이터와 함수를 하나의 객체로 묶는 것 - 캡슐화(encapsulation)

4.3 객체는 무엇으로 구성되는가?
  • 멤버 변수(member variable)
  • 멤버 함수(member function)

4.4 클래스는 객체의 설계도
#include <iostream>
using namespace std;

// Circle 클래스
class Circle {
public:
	int r;
	string color;

	double area() {
		return 3.14 * r * r;
	}
};

int main() {
	Circle obj;  // 객체 쟁성
	obj.r = 100;
	obj.color = "blue";

	cout << "원의 면적 = " << obj.area() << endl;
	return 0;
}

 

▶ 여러 개의 객체 생성

#include <iostream>
using namespace std;

class Circle {
public:
	int r;
	string color;

	double area() {
		return 3.14 * r * r;
	}
};

int main() {
	Circle pizza1, pizza2;  // 객체 두 개

	pizza1.r = 100;
	pizza1.color = "yellow";
	cout << "피자의 면적 = " << pizza1.area() << endl;

	pizza2.r = 200;
	pizza2.color = "white";
	cout << "피자의 면적 = " << pizza2.area() << endl;

	return 0;
}

사각형을 클래스로 나타내자
#include <iostream>
using namespace std;

class Rect {
public:
	int w, h;
	int area() {
		return w * h;
	}
};

int main() {
	Rect myRect;
	myRect.w = 3;
	myRect.h = 4;
	
	cout << "사각형의 넓이: " << myRect.area() << endl;

	return 0;
}

Car 클래스 작성
#include <iostream>
using namespace std;

class Car {
public:
	int speed;
	int gear;
	string color;

	void speedUP() {
		speed += 10;
	}

	void speedDOWN() {
		speed -= 10;
	}
};

int main() {
	Car myCar;

	myCar.speed = 100;
	myCar.gear = 3;
	myCar.color = "red";

	myCar.speedUP();
	myCar.speedDOWN();

	return 0;
}

4.5 멤버 함수 중복 정의

: 멤버 함수도 함수의 일종이므로 중복 정의가 가능하다.

#include <iostream>
#include <string>
using namespace std;

class PrintData {
public:
	void print(int i) {
		cout << i << endl;
	}
	void print(double f) {
		cout << f << endl;
	}
	void print(string s = "No Data!") {
		cout << s << endl;
	}
};

int main() {
	PrintData obj;

	obj.print(1);
	obj.print(3.14);
	obj.print("C++ is cool.");

	return 0;
}

4.6 클래스의 인터페이스와 구현의 분리

: 멤버 함수를 클래스 외부에 작성할 수 있다.

#include <iostream>
#include <string>
using namespace std;

class Circle {
public:
	double area();

	int r;
	string color;
};

// 클래스 외부에서 멤버 함수 정의
double Circle::area() {
	return 3.14 * r * r;
}

int main() {
	Circle c;

	c.r = 10;
	cout << c.area() << endl;

	return 0;
}

 

▶ 이름 공간(name space)

: 식별자(자료형, 함수, 변수 등의 이름)의 영역

using namespace std;
using namespace sfml;
...

4.7 객체 지향 프로그래밍의 개념들

▶ 캡슐화

: 코드를 재사용하기 위해서는 코드 자체가 잘 정리되어 있어야 한다.

  • 객체(object): 하나의 캡슐
  • 정보 은닉(information hiding): 객체를 캡슐로 싸서 객체의 내부를 보호하는 것

 

▶ 상속과 다형성

  • 상속: 기존의 코드를 재활용하기 위한 기법으로, 이미 작성된 클래스(부모 클래스)를 이어받아서 새로운 클래스(자식 클래스)를 생성하는 기법

// Shape 클래스를 정의하고, 이것을 상속받아서 Rect 클래스 정의한다.

class Shape {
protected:
	int x, y;
public:
	void draw() {}
	void move() {}
};

class Rect :Shape {
public:
	int w, h;
	int area() {
		return w * h;
	}
};

4.8 UML
  • UML(Unified Modeling Language): 대표적인 클래스 다이어그램(class diagram) 표기법