您好,欢迎访问一九零五行业门户网

多态性的类型 - 临时、包含、参数化和强制

在这里我们将看到不同类型的多态性。类型为 -
ad-hoc包含参数化强制 ad-hoc 多态性称为重载。这允许具有相同名称的函数针对不同的类型以不同的方式起作用。函数和运算符都可以重载。有些语言不支持运算符重载,但函数重载很常见。
示例#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;}
输出addition of numbers: 9addition of strings: helloworld
包含多态性称为子类型化。这允许使用基类指针和引用来指向派生类。这就是运行时多态性。在执行之前我们不知道实际对象的类型。我们需要 c++ 中的虚函数来实现这种包含多态性。
示例#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();}
输出this is base class.this is derived class.
强制多态称为强制转换。当对象或基元被转换为某种其他类型时,就会发生这种类型的多态性。铸造有两种类型。隐式转换是使用编译器本身完成的,显式转换是使用 const_cast、dynamic_cast 等完成的。
示例#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);}
输出value is: 100value 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;}
输出max of (156, 78): 156max of (a, x): x
以上就是多态性的类型 - 临时、包含、参数化和强制的详细内容。
其它类似信息

推荐信息