いつも何らかの言語を学ぶと継承らへんで止まってたんですが、、
今度こそは違うぞ!ポリモーフィズムやでえ!
まず、ポリモーフィズムはとは、なんですか?
これは下記リンク参(ry
capm-network.com
引用すると、
まあよーわかりませんね
後日色々と学んでみると、とりあえずポリモーフィズムはクラスの継承がある場合に、関数呼び出し元を変えずに関数呼び出し先を変えるという概念だそう。
これによって様々なメソッドが作れるということですね、、
下記の例はなんかむずい。(12/3/2019追記)
ただ、重要な言葉として"Dynamic Binding" がポリモーフィズムを指してしそうです。
実際にコードを見て、なぜこれが必要なのか確認。
#include <iostream> class Base { public: void say_hello() const{ std::cout << "this is Base class object" << std::endl; } }; class Derived: public Base { public: void say_hello() const { std::cout << "this is Derived class object" << std::endl; } }; void greetings(const Base &obj){ std::cout << "Hello! : "; obj.say_hello(); } int main(){ Base b; Derived d; b.say_hello(); d.say_hello(); greetings(b); greetings(d); Base *ptr = new Derived(); ptr->say_hello(); delete ptr; return 0; }
上記のようなコードの結果は下記。
this is Base class object this is Derived class object Hello! : this is Base class object Hello! : this is Base class object this is Base class object
メッセージの下から二つが問題なんです。
Derivedクラスのsay_helloファンクションを呼びたいと思っても、Baseクラスが呼ばれちゃうからです。
functionも、ポインタ作成時もBaseクラスを基底にしているので。。
じゃあどうするの?というときにポリモーフィズムがやってきます。
長くなったので次記事で紹介w