객체 - 오브젝트
실체 - 인스턴스
<예제 3-1> Circle 클래스의 객체 생성 및 활용
#include <iostream>
using namespace std; //이름 충돌 방지
class Circle {
public: //public으로 선언해주었음
int radius;
double getArea();
}; //Circle 선언부
double Circle::getArea() {
return 3.14 * radius * radius;
} //Circle 구현부
int main() {
Circle donut; //객체 donut 생성
donut.radius = 1; //donut의 멤버 변수 접근
double area = donut.getArea(); //donut의 멤버 함수 호출
cout << "donut 면적은 " << area << endl;
Circle pizza;
pizza.radius = 30;
area = pizza.getArea();
cout << "pizza 면적은 " << area << endl;
}
<예제 3-2> Rectangle 클래스 만들기
#include <iostream>
using namespace std;
class Rectangle { //Rectangle 클래스 선언부
public:
int width;
int height;
double getArea(); //면적을 계산하여 리턴하는 함수
};
double Rectangle::getArea() { //Rectangle 클래스 구현부
return width * height;
}
int main() {
Rectangle rect;
rect.width = 3;
rect.height = 5;
cout << "사각형의 면적은 " << rect.getArea() << endl;
}
<예제 3-3> 2개의 생성자를 가진 Circle 클래스
#include <iostream>
using namespace std;
class Circle {
public:
int radius;
Circle(); //매개변수 없는 생성자
Circle(int r); //매개변수 있는 생성자
double getArea();
};
Circle::Circle() {
radius = 1;
cout << "반지름 " << radius << " 원 생성" << endl;
}
Circle::Circle(int r) {
radius = r;
cout << "반지름 " << radius << " 원 생성" << endl;
}
double Circle::getArea() {
return 3.14 * radius * radius;
}
int main() {
Circle donut; //매개 변수 없는 생성자 호출 -> Circle(); 자동호출
double area = donut.getArea();
cout << "donut 면적은 " << area << endl;
Circle pizza(30); //매개 변수 있는 생성자 호출 -> Circle(30); 자동호출
area = pizza.getArea();
cout << "pizza 면적은 " << area << endl;
}
다양한 생성자의 멤버 변수 초기화 방법
<예제 3-5> 멤버변수의 초기화와 위임 생성자 활용
Point::Point{x=0; y=0;}
Point::Point(int a, int b){x=a; y=b;}
//x,y를 생성자 서두에 초기값으로 초기화하고 위임 생성자를 이용
->
Point::Point():Point(0,0){ } //위임 생성자
Point::Point(int a, int b) //타겟 생성자
:x(a), y(b){ }
Q . 생성자는 꼭 있어야하는가? : 예
class Circle{
Circle(); //기본 생성자
}
<예제 3-6> Rectangle 클래스 만들기
#include <iostream>
using namespace std;
class Rectangle {
public:
int width;
int height;
Rectangle();
Rectangle(int w);
Rectangle(int w,int h); //3개의 생성자가 필요함
bool isSquare();
};
Rectangle::Rectangle() {
height=width = 1;
}
Rectangle::Rectangle(int w) {
height=width = w;
}
Rectangle::Rectangle(int w,int h) {
width = w;
height =h;
}
bool Rectangle::isSquare() {
if (width == height) {
return true;
}
else return false;
}
int main() {
Rectangle rect1;
Rectangle rect2(3, 5);
Rectangle rect3(3);
if (rect1.isSquare()) cout << "rect1은 정사각형이다." << endl;
if (rect2.isSquare()) cout << "rect2은 정사각형이다." << endl;
if (rect3.isSquare()) cout << "rect3은 정사각형이다." << endl;
}
class Circle{
~Circle(); //소멸자 함수 선언
}
Circle::~Circle(){
}
<예제 3-7> Circle 클래스에 소멸자 작성 및 실행
<예제 3-8> 지역 객체와 전역 객체의 생성 및 소멸 순서
-> 순서
프로그램 로딩 : (globalDonut, globalPizza)
main() 함수 시작 : (mainDonut, mainPizza)
f() 함수 실행 : (fDonut, fPizza)
private(디폴트): 동일한 클래스의 멤버 함수에만 제한
public: 모든 다른 클래스에 허용
protected: 클래스 자신과 상속받은 자식 클래스에만 허용
클래스 선언부: 헤더파일
클래스 구현부: cpp파일
main등 전역 함수나 변수는 다른 cpp파일에