C++/공부내용
C++ Classes - Polymorphism
HappyFrog
2022. 6. 30. 14:54

다형성
다형성이란 "여러 형질을 갖는다"는 의미입니다. 그리고 이것은 우리가 서로 상속하는 많은 클래스를 가질 때 나타납니다.
우리가 이전 챕터에서 특정했던 것처럼; 상속은 다른 클래스의 메서드와 속성을 상속하게 해줍니다. 다형성은 그 메서드들을 이용해 서로 다른 업무를 수행합니다. 이것은 우리가 또 다른 방식으로 단일 행동을 수행할 수 있습니다.
예를 들면, Animal 이라고 불리는 기반클래스는 animalSound() 라는 메서드를 가지고 있습니다. Animal의 파생클래스인 Pigs, Cats, Dogs, Birds가 있으며 그들은 그들 고유의 animal sound를 구현합니다.
예시
// 기반 클래스
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n";
}
};
// 파생 클래스
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
};
// 파생 클래스
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n";
}
};
이제 우리는 Pig 와 Dog 객체를 만들고 animalSound()에 재정의하는게 가능해졌습니다:
예시
#include <iostream>
using namespace std;
// 기반 클래스
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n";
}
};
// 파생 클래스
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
};
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n";
}
};
int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
