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


本文向大家介绍多态性的类型-临时,包含,参数和强制,包括了多态性的类型-临时,包含,参数和强制的使用技巧和注意事项,需要的朋友参考一下

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

  • 特别指定

  • 包容性

  • 参数

  • 强迫

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 << "这是基类。" << endl;
      }
};
class Derived : public Base {
   public:
      void print() {
         cout << "这是派生类。" << 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();
}

输出结果

这是基类。
这是派生类。

强制转换多态性称为强制转换。当对象或图元被转换为其他类型时,会发生这种类型的多态。有两种类型的铸件。隐式转换是使用编译器本身完成的,显式转换是使用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