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

WBOY
WBOY 转载
2023-09-23 10:21:04 956浏览

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

在这里我们将看到不同类型的多态性。类型为 -

  • 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: 9
Addition 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: 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;
}

输出

Max of (156, 78): 156
Max of (A, X): X

以上就是多态性的类型 - 临时、包含、参数化和强制的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除