C++ 다형성


다형성

다형성은 "많은 형태"를 의미하며 상속에 의해 서로 연결된 많은 클래스가 있을 때 발생합니다.

이전 장에서 지정한 것처럼; 상속 을 통해 다른 클래스의 속성과 메서드를 상속할 수 있습니다. 다형성 은 이러한 방법을 사용하여 다른 작업을 수행합니다. 이를 통해 우리는 다양한 방식으로 단일 작업을 수행할 수 있습니다.

예를 들어 라는 Animal메서드가 있는 이라는 기본 클래스를 생각해 보십시오 animalSound(). 동물의 파생 클래스는 돼지, 고양이, 개, 새가 될 수 있습니다. 또한 동물 소리(돼지 울음소리, 고양이 야옹 소리 등)가 자체적으로 구현되어 있습니다.

예시

// Base class
class Animal {
  public:
    void animalSound() {
    cout << "The animal makes a sound \n" ;
  }
};

// Derived class
class Pig : public Animal {
  public:
    void animalSound() {
    cout << "The pig says: wee wee \n" ;
  }
};

// Derived class
class Dog : public Animal {
  public:
    void animalSound() {
    cout << "The dog says: bow wow \n" ;
  }
};

상속 장 에서 우리 :는 클래스에서 상속하기 위해 기호를 사용 한다는 것을 기억하십시오 .

이제 Pig Dog개체 를 만들고 animalSound()메서드를 재정의할 수 있습니다.

예시

// Base class
class Animal {
  public:
    void animalSound() {
    cout << "The animal makes a sound \n" ;
  }
};

// Derived class
class Pig : public Animal {
  public:
    void animalSound() {
    cout << "The pig says: wee wee \n" ;
   }
};

// Derived class
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;
}

왜 그리고 언제 "상속"과 "다형성"을 사용해야 합니까?

- 코드 재사용성에 유용합니다. 새 클래스를 만들 때 기존 클래스의 속성과 메서드를 재사용합니다.