프로그램 접근 level
public | 프로그램 어디에서도 접근 |
private | 같은 class내, friend로 선언된 함수나 class에 의한 접근 |
protected | 같은 class내, 서브 class, friend에 의한 접근 |
Class 선언
class Rectangle {
public: // 4개의 public 멤버 함수
Rectangle(); // 생성자
~Rectangle(); // 파괴자
int GetHeight(); // 사각형 높이 반환
int GetWidth(); // 사각형 길이 반환
private: // 4개의 private 데이터 멤버
int xLow, yLow, height, width;
};
Class 정의 밖에서 멤버 함수 구현시 접두어 필요
int Rectangle::GetHeight() {return height;}
int Rectangle::GetWidth() {return width;}
class 멤버 접근 방법 2가지
- 직접 접근
- 포인터 통한 접근
main() {
Rectangle r, s; // class Rectangle의 객체 r, s
Rectangle *t &s; // class 객체 s에 대한 포인터 t
// 클래스 객체 멤버 직접 접근시 . 사용
// 클래스 객체 멤버 포인터 통해 접근시 -> 사용
if (r.GetHeight() * r.GetWidth() > t->GetHeight() * t->Getwidth())
cout<<"r";
else
cout<<"s";
cout<<"has the greater area"<<endl;
}
생성자 : 객체의 데이터 멤버 초기화. class 객체 생성시 자동 실행
파괴자 : 객체 소멸 직전 데이터 멤버 삭제. 생성자 이름 앞에 틸드(~) 사용
// 생성자
Rectangle::Rectangle(int x, int y, int h, int w){
xLow=x; yLow=y;
height=h; width=w;
}
// 묵시적 생성자
Rectangle::Rectangle(int x=0, int y=0, int h=0, int w=0)
:xLow(x), yLow(y), height(h), width(w)
{}
struct과 class
struct은 묵시적 public인 점을 제외하고 class와 동일
static 클래스 데이터 멤버는 전역 변수로 생각.
class A{
public:
int i;
}
A x1, y1;
x1.i = 20; y1.i=30;
cout << x1.i; // 20
class B {
public:
static int j;
}
B x2, y2;
x2.j = 20; y2.j =30;
cout << x2.j; // 30
'알고리즘 > C++' 카테고리의 다른 글
3. 스택 (Stack) (0) | 2020.07.21 |
---|---|
Container Class와 Template (0) | 2020.07.13 |
2. 배열 (Array) (0) | 2020.07.13 |
C++ 배열 동적할당 (0) | 2020.06.23 |
C 배열 동적할당 (0) | 2020.06.21 |