C++ ポリモーフィズム
C++ は、ポリモーフィズムを含む多くの強力な機能を備えたオブジェクトベースのプログラミング言語です。ポリモーフィズムとは、オブジェクトの異なるプロパティが同じ動作を示す可能性があることを意味します。C++ には、コンパイル時ポリモーフィズムと実行時ポリモーフィズムの 2 種類のポリモーフィズムがあります。
コンパイル時のポリモーフィズム
コンパイル時のポリモーフィズムは、関数のオーバーロードとテンプレートによって実現されます。関数のオーバーロードとは、同じ名前でパラメーターの型が異なる複数の関数を同じスコープ内で定義することを指します。C++ コンパイラは、関数呼び出しのパラメーターの型に基づいて、呼び出す関数を選択します。例えば:
void print(int num) {
cout << "Integer: " << num << endl;
}
void print(double num) {
cout << "Double: " << num << endl;
}
int main() {
int a = 5;
double b = 3.14;
print(a);
print(b);
return 0;
}
出力は次のとおりです。
Integer: 5
Double: 3.14
テンプレートは、コード構造は同じだがデータ型が異なる関数またはクラスを作成するために使用できる一般的なプログラミング メカニズムです。例えば:
template<typename T>
void print(T num) {
cout << "Value: " << num << endl;
}
int main() {
int a = 5;
double b = 3.14;
print(a);
print(b);
return 0;
}
出力は上記の例と同じです。
ランタイムポリモーフィズム
実行時のポリモーフィズムは、仮想関数と継承を通じて実現されます。仮想関数とは、基本クラスで仮想関数として宣言された関数を指し、派生クラスでオーバーライドできます。派生クラス オブジェクトがこの関数を呼び出すと、クラス内の関数ではなく、派生クラス内の関数が呼び出されます。基本クラス。例えば:
class Shape {
public:
virtual void draw() {
cout << "Drawing a generic shape." << endl;
}
};
class Rectangle : public Shape {
public:
void draw() {
cout << "Drawing a rectangle." << endl;
}
};
class Circle : public Shape {
public:
void draw() {
cout << "Drawing a circle." << endl;
}
};
int main() {
Shape* shape1 = new Rectangle();
Shape* shape2 = new Circle();
shape1->draw();
shape2->draw();
return 0;
}
出力は次のとおりです。
Drawing a rectangle.
Drawing a circle.
継承とは、派生クラスが基本クラスのメンバー変数とメンバー関数を継承できることを意味します。例えば:
class Animal {
public:
void speak() {
cout << "Generic animal sound." << endl;
}
};
class Dog : public Animal {
public:
void speak() {
cout << "Bark!" << endl;
}
};
int main() {
Animal* animal1 = new Animal();
Animal* animal2 = new Dog();
animal1->speak();
animal2->speak();
return 0;
}
出力は次のとおりです。
Generic animal sound.
Bark!
アプリケーション
ポリモーフィズムは、グラフィカル インターフェイス プログラミングのコントロール、ゲーム開発のキャラクターや NPC など、多くのシナリオに適用できます。以下は簡単な応用例です。
class Shape {
public:
virtual void draw() = 0;
};
class Rectangle : public Shape {
public:
void draw() {
cout << "Drawing a rectangle." << endl;
}
};
class Circle : public Shape {
public:
void draw() {
cout << "Drawing a circle." << endl;
}
};
int main() {
vector<Shape*> shapes;
shapes.push_back(new Rectangle());
shapes.push_back(new Circle());
for (int i = 0; i < shapes.size(); i++) {
shapes[i]->draw();
}
return 0;
}
出力は次のとおりです。
Drawing a rectangle.
Drawing a circle.
この例では、純粋仮想関数とベクトル コンテナーを使用して、複数のシェイプ オブジェクトを管理しました。長方形でも円でも、同じdraw()関数を呼び出すことで描画できます。
要約すると、C++ のポリモーフィズムは、コードの再利用性と柔軟性を高める非常に便利なプログラミング メカニズムです。コード構造を最適化し、プログラムの効率を向上させるために、適切な状況でポリモーフィズムを使用することをお勧めします。