[C++] 4. 클래스

Sireal·2022년 2월 17일
0

객체 : 해당 변수들과 관련 데이터들로 이루어진 소프트웨어 덩어리
한 덩어리라고 생각하자.

클래스

C++에서 객체를 만들때 class 를 선언하여 사용한다.

#include <iostream>

class Animal{
	int food;
	int weight;

public:
	void set_animial(int _food, int _weight){
		food = _food;
		weight = _weight;
	}
	
	void increase_food(int inc){
		food += inc;
		weight += (inc/3);
	}
	void view_stat(){
		std::cout << " this Animal's food : " << food <<std::endl;
		std::cout << " this Animal's weight : " << weight << std::endl;
	}
};	// 클래스 선언 시 세미클론 꼭 붙이기

int main(){
	Animal animal;
	animal.set_animial(100, 50);
	animal.increase_food(30);

	animal.view_stat();
	return 0;
}

  • 구조체와 시퀀스가 굉장히 유사하다.
    • 다만 struct 와 같은 class같은걸 안붙여주고 그냥 클래스 이름을 써서 사용하면 됨.

클래스 내부를 살펴보자

class Animal{
private:
	int food;
	int weight;
public:
	void set_animial(int _food, int _weight){
		food = _food;
		weight = _weight;
	}	
	void increase_food(int inc){
		food += inc;
		weight += (inc/3);
	}
	void view_stat(){
		std::cout << " this Animal's food : " << food <<std::endl;
		std::cout << " this Animal's weight : " << weight << std::endl;
	}
};	// 클래스 선언 시 세미클론 꼭 붙이기

임의로 만들어진 클래스 설계도 같은 느낌이라 보면됨.

  • 멤버변수, 함수
    • 멤버변수 : int food, weight 와 같은 클래스 내에 변수들
    • 멤버함수 : set_animal, increase_food 와 같은 클래스 내에 함수들
  • 접근 지시자
    • private : 그 클래스만 접근가능. (캡슐화)
    • public : 누구나 접근 가능.
    • protected : 그 클래스와 자식 클래스까지만 접근 가능.
  • 멤버변수, 함수는 default값으로 private 이다.

참고 : 씹어먹는 C++

profile
🚄계속 앞으로🚄

0개의 댓글

관련 채용 정보