객체와 객체 포인터의 차이
class Pet
{
public:
int _hp = 100;
int _age = 3;
};
int main()
{
Pet pet;
Pet* pet = new Pet();
return 0;
}
포인터로 선언해야 하는 이유?
- 상속 관계에 있는 클래스들을 바꿔가며 사용할 경우
- 생명주기의 관리를 각각 해야할 경우
- 클래스 안에 클래스를 가질 경우, 크기가 비대해지는 것을 방지
1. 상속 관계에 있는 클래스들을 바꿔가며 사용할 경우
#include<iostream>
using namespace std;
class Pet
{
public:
int _hp = 100;
int _age = 3;
};
class RabbitPet : public Pet
{
public:
RabbitPet(int color) : _color(color)
{
}
public:
int _color;
};
class TurtlePet : public Pet
{
public:
TurtlePet(int sex) : _sex(sex)
{
}
public:
int _sex;
};
int main()
{
RabbitPet rabbitPet(1111);
TurtlePet turtlePet(00);
Pet pet;
pet = (Pet)rabbitPet;
RabbitPet* rabbitPetPtr = new RabbitPet(2222);
TutlePet* turtlePetPtr = new TurtlePet(11);
Pet* petsPtr[2];
petsPtr[0] = rabbitPetPtr;
petsPtr[1] = turtlePetPtr;
cout << ((RabbitPet*)petsPtr[0])->_color << endl;
return 0;
}
2. 생명주기의 관리를 각각 해야할 경우
3. 클래스 안에 클래스를 가질 경우, 크기가 비대해지는 것을 방지
#include<iostream>
using namespace std;
class Pet
{
public:
int _hp = 100;
int dummy[500];
};
class RabbitPet : public Pet
{
public:
RabbitPet(int color) : _color(color)
{
}
public:
int _color;
};
class TurtlePet : public Pet
{
public:
TurtlePet(int sex) : _sex(sex)
{
}
public:
int _sex;
};
class Player
{
public:
Player(Pet* pet) : _pet(pet)
{
}
~Player()
{
delete _pet;
}
public:
Pet* _pet;
};
int main()
{
Player* player1 = new Player(new RabbitPet(1111));
Player* player2 = new Player(new TurtlePet(1));
delete player1;
delete player2;
return 0;
}