C++/class

[C++] 클래스에 대한 이해(Car.cpp)

year.number 2022. 6. 24. 10:00

Key Point

1. 클래스란 서로 관련이 있는 변수와 함수들을 한 곳으로 모은 것이다.
2. 객체가 생성될 때 멤버 변수는 별도로 생성되고, 멤버 함수는 공유된다.
3. 멤버 변수와 멤버 함수에 접근하기 위해 .(dot operator)를 사용한다. (점 앞의 객체에게 점 뒤에 있는 것을 가져다 달라는 의미)

 

#include <iostream>
#include <string>
using namespace std;

// ========== <STEP 1> ==========

class Car{
    
    
    // 멤버 변수
public:
    int speed;
    int gear;
    string color;
    
    
    // 멤버 함수
    void speedUp(){
        speed += 10;
    }
    
    void sppedDown(){
        speed -= 10;
    }
    
};


int main(){
    // ========== <STEP 2> ==========
    
    // 객체 생성
    Car myCar;
    
    
    // ========== <STEP 3> ==========
    
    // 메시징
    myCar.speed = 100;
    myCar.color = "white";
    
    myCar.speedUp();
    myCar.speedUp();
    
    cout << myCar.speed << endl;

    return 0;
}