多态类型 - 临时、包含、参数化和强制转换
本文中,我们将探讨不同类型的多态性。
- 临时多态性
- 包含多态性
- 参数化多态性
- 强制转换多态性
临时多态性被称为“重载”。这可以让具有相同名称的方法根据不同类型采取不同的行为。函数和运算符都可以被重载。一些语言不支持运算符重载,但函数重载却很常见。
示例
#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
广告
数据结构
网络化
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP