class Rectangle {
public:
int width;
int height; // 멤버 변수
int getArea(); // 멤버 함수
};
Rectangle 이라는 이름의 class를 선언하였다.
public은 접근 지정자로 외부에서 접근할 수 있게 해준다.
접근 지정자를 쓰지 않는다면, 기본값은 private로 설정되어 외부에서 접근할수 없다.
int Rectangle::getArea() {
return width * height;
}
class의 멤버변수는 class 밖에서 선언할 수 있다.
멤버 함수를 private에 정의하면 오류가 발생한다!
#include <iostream>
using namespace std;
class Rectangle {
public:
int width;
int height;
int getArea();
};
int Rectangle::getArea() {
return width * height;
}
int main() {
Rectangle rect;
rect.width = 3;
rect.height = 5;
cout << "사각형의 면적은 " << rect.getArea() << endl;
}
Rectangle 의 객체인 rect 를 생성했다.
rect.width 처럼 .을 찍어 객체의 멤버에 접근할 수 있다.
함수도 마찬가지로 rect.getArea() 로 사용할 수 있다.

'c++' 카테고리의 다른 글
| string 클래스 (0) | 2020.04.19 |
|---|---|
| C++ 동적 메모리 할당 (0) | 2020.04.19 |
| 명품 C++ 프로그래밍 Open Challenge 3장 (0) | 2020.04.18 |
| 헤더파일과 cpp 파일의 분리 (0) | 2020.04.18 |
| class 의 생성자 (0) | 2020.04.17 |