2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C++】基礎を学ぶ⑳~多態性~

Last updated at Posted at 2022-07-17

多態性

多態性とは、同じ名前の関数を呼び出して異なる処理を実行すること
ポリモーフィズムとも呼ばれる
オーバーロードオーバーライドで実現することができる

オーバーロード

1つのプログラムに同じ名前引数の数型が違う関数を作成すること

オーバーロードを用いたプログラム

#include <iostream>
using namespace std;
 
class Human {
  public:
    void show(){
      cout << "引数なしのshow関数" << endl;
    }
    void show(string str){
      cout << "引数が" << str << "のshow関数" << endl;
    }
};

int main() {
  Human human;
  human.show();
  human.show("Taro");
  return 0;
}
引数なしのshow関数
引数がTaroのshow関数

オーバーライド

基底クラスで関数を継承した派生クラスで独自に定義しなおして上書きすること
基底クラスのオーバーライドする関数にvirtualをつける
基底クラスでオーバーライドされる関数のことを仮想関数という

オーバーライドを用いたプログラム

#include <iostream>
using namespace std;
 
class Human {
  public:
    virtual void show(){
      cout << "Human class" << endl;
    }
};

class Student : public Human{
  public:
    void show(){
      cout << "Student class" << endl;
    }
};

int main() {
  Human human;
  human.show();
  Student student;
  student.show();
  return 0;
}
Human class
Student class

派生クラスから仮想関数を呼び出す

以下のように書くことで派生クラスから継承元の基底クラスの仮想関数を呼び出すことができます

派生クラスのオブジェクト.基底クラス::仮想関数名;

サンプルプログラム

#include <iostream>
using namespace std;
 
class Human {
  public:
    virtual void show(){
      cout << "Human class" << endl;
    }
};

class Student : public Human{
  public:
    void show(){
      cout << "Student class" << endl;
    }
};

int main() {
  Student student;
  student.Human::show();
  return 0;
}
Human class

次の記事

【C++】基礎を学ぶ㉑~テンプレート~

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?