C++/class

[C++] 객체의 동적 생성

year.number 2022. 7. 1. 00:50

 

정적 메모리 할당으로 객체 생성 동적 메모리 할당으로 객체 생성
 Car myCar; Car *pCar = new Car();

pCar은 동적 생성된 객체의 주소를 저장한다.

 

객체 포인터의 메세징 방법: -> arrow 연산자 이용

 

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

class Car{
private:
    int speed;
    int gear;
    string color;
    
public:
    Car(int s = 0, int g = 1, string c = "grey") : speed(s), gear(g), color(c){}
    void display();
};

void Car::display(){
    cout << "속도: " << speed << " 기어: " << gear << " 컬러 " << color << endl;
}

int main(){
    //정적 메모리 할당
    Car c1;
    c1.display();
    
    //객체 포인터로 객체를 가리키게 함
    Car *pCar = &c1;
    pCar -> display();
    
    //동적 메모리 할당으로 객체 생성
    pCar = new Car(0, 1, "blue");
    pCar -> display();
    delete pCar;
    
    
    return 0;
}