Functional-programming-polymorphism
提供:Dev Guides
関数型プログラミング-多態性
プログラミングの観点では、ポリモーフィズムとは、単一のコードを複数回再利用することを意味します。 より具体的には、データ型またはクラスに応じてオブジェクトを異なる方法で処理するプログラムの機能です。
多型は2つのタイプです-
- コンパイル時ポリモーフィズム-このタイプのポリモーフィズムは、メソッドのオーバーロードを使用して実現できます。
- 実行時ポリモーフィズム-このタイプのポリモーフィズムは、メソッドのオーバーライドと仮想関数を使用して実現できます。
多型の利点
多態性には、次の利点があります-
- プログラマーがコードを再利用するのに役立ちます。つまり、一度作成、テスト、実装されたクラスは必要に応じて再利用できます。 多くの時間を節約します。
- 単一の変数を使用して、複数のデータ型を格納できます。 *コードのデバッグが簡単。
多態的なデータ型
ポリモーフィックデータ型は、バイトアドレスのみを格納するジェネリックポインターを使用して実装でき、そのメモリアドレスに格納されるデータのタイプはありません。 例えば、
function1(void* p, void *q)
ここで、 p および q は、 int、float (またはその他の)値を引数として保持できる汎用ポインターです。
C ++の多態性関数
次のプログラムは、オブジェクト指向プログラミング言語であるC ++で多態性関数を使用する方法を示しています。
#include <iostream>
Using namespace std:
class A {
public:
void show() {
cout << "A class method is called/n";
}
};
class B:public A {
public:
void show() {
cout << "B class method is called/n";
}
};
int main() {
A x; //Base class object
B y; //Derived class object
x.show(); //A class method is called
y.show(); //B class method is called
return 0;
}
それは次の出力を生成します-
A class method is called
B class method is called
Pythonの多態性関数
次のプログラムは、関数型プログラミング言語であるPythonでポリモーフィック関数を使用する方法を示しています。
class A(object):
def show(self):
print "A class method is called"
class B(A):
def show(self):
print "B class method is called"
def checkmethod(clasmethod):
clasmethod.show()
AObj = A()
BObj = B()
checkmethod(AObj)
checkmethod(BObj)
それは次の出力を生成します-
A class method is called
B class method is called