Rumah >pembangunan bahagian belakang >C++ >Jenis polimorfisme - sementara, terkandung, parameter dan paksaan
Di sini kita akan melihat pelbagai jenis polimorfisme. Jenis ialah -
#include<iostream> using namespace std; int add(int a, int b) { return a + b; } string add(string a, string b) { return a + b; //concatenate } int main() { cout << "Addition of numbers: " << add(2, 7) << endl; cout << "Addition of Strings: " << add("hello", "World") << endl; }Output
Addition of numbers: 9 Addition of Strings: helloWorld
#include<iostream> using namespace std; class Base { public: virtual void print() { cout << "This is base class." << endl; } }; class Derived : public Base { public: void print() { cout << "This is derived class." << endl; } }; int main() { Base *ob1; Base base_obj; Derived derived_obj; ob1 = &base_obj; //object of base class ob1->print(); ob1 = &derived_obj; //same pointer to point derived object ob1->print(); }Output
This is base class. This is derived class.
#include<iostream> using namespace std; class Integer { int val; public: Integer(int x) : val(x) { } operator int() const { return val; } }; void display(int x) { cout << "Value is: " << x << endl; } int main() { Integer x = 50; display(100); display(x); }Output
Value is: 100 Value is: 50
#include<iostream> using namespace std; template <class T> T maximum(T a, T b) { if(a > b) { return a; } else { return b; } } int main() { cout << "Max of (156, 78): " << maximum(156, 78) << endl; cout << "Max of (A, X): " << maximum('A', 'X') << endl; }Output
Max of (156, 78): 156 Max of (A, X): X
Atas ialah kandungan terperinci Jenis polimorfisme - sementara, terkandung, parameter dan paksaan. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!