반응형
C++ Everything in an object.
1.What is an object?
Deepsleep boy; boy.play(); // 내가 (boy가) Play 를 한다. boy.sleep(); // 내가 deepsleep 을 한다.
play 함수에 boy를 인자로 주지 않아도 되는데, 내가 play를 하는 것이기 때문에 내 정보는 이미 play함수가 다 알고 있는 상황이다. play함수는 나의 모든 것을 알고 있기에 낭 대한 적절한 처리를 할 수 있게 된다. 즉 boy는 상태를 알려주는 변수와, 하는 행동을 수행하는 함수들로 구성되고 있다. 결국 객체는 변수들과 관련된 함수들로 이루어진 소프트웨어 꾸러미.
아래 그림과 같은 느낌?
객체는 자기만의 정보를 나타내는 변수와 정보를 이용해 작업을 하는 함수들로 이루어져 있다.
보통 인스턴스 변수와 인스턴트 메소드라고 불리우고, 그림 구성이 저런 식인 이유는 진짜로 변수들이 외부로부터 보호받고 있기 때문이다.
즉 외부에서 객체의 인스턴스 변수의 값을 바꾸지 못하고 오직 인스턴스 함수를 통해서만 가능하다.
People house; people.house += 10; // --> 불가능 people.increase_house(10); // --> 가능
2.About the class.
클래스는 객체의 설계도.
C++에서 클래스를 이용해서 만들어진 객체를 인스턴스라고 한다.
예시를 들어 보겠다.
#includeusing namespace std; class Animal { private: int food; int weight; public: void set_animal(int _food, int _weight) { food = _food; weight = _weight; } void increase_food(int inc) { food += inc; weight += (inc / 3); } void view_stat() { cout << "이 동물의 food : " << food << endl; cout << "이 동물의 weight : " << weight << endl; } }; int main() { Animal animal; animal.set_animal(100, 50); animal.increase_food(30); animal.view_stat(); return 0; }
코드를 분석해보면, Animal animal; 은 Animal 클래스의 인스턴스 animal을 만들게 된 것이다.
물론 구조체에서 구조체 변수를 생성할 때는 struct를 써야 한다.
class Animal
{
private:
int food;
int weight;
public:
void set_animal(int _food, int _weight)
{
food = _food;
weight = _weight;
}
void increase_food(int inc)
{
food += inc;
weight += (inc / 3);
}
void view_stat()
{
cout << "이 동물의 food : " << food << endl;
cout << "이 동물의 weight : " << weight << endl;
}
};
private:
int food;
int weight;
public:
void set_animal(int _food, int _weight)
{
food = _food;
weight = _weight;
}
void increase_food(int inc)
{
food += inc;
weight += (inc / 3);
}
void view_stat()
{
cout << "이 동물의 food : " << food << endl;
cout << "이 동물의 weight : " << weight << endl;
}
void set_animal(int _food, int _weight)
{
food = _food;
weight = _weight;
}
반응형
'#Programming Language > C++' 카테고리의 다른 글
C++ Your Own String Class (0) | 2018.04.01 |
---|---|
C++ Object-oriented programming. (0) | 2018.03.30 |
C++ Features of C ++ only. (0) | 2018.03.30 |
C++ The difference between C and C ++. (0) | 2018.03.29 |
C++ Common in C and C ++. (0) | 2018.03.29 |