多态是面向对象编程的关键特征,即具有多种形式。在C ++中,这分为编译时多态和运行时多态。
编译时多态的一个示例是函数重载或运算符重载。函数覆盖是运行时多态性的一个示例。
C ++中使用函数重载的多态示例如下。
示例#include
using namespace std;
class Example {
public :
void func(int a) {
cout <
}
void func(int a, int b) {
cout <
cout <
}
void func(char c) {
cout <
}
};
int main() {
Example obj;
cout<
obj.func(5);
cout<
obj.func('A');
cout<
obj.func(7, 2);
return 0;
}
输出结果
上面程序的输出如下。One int value
The value of a: 5
One char value
The value of c: A
Two int values
The value of a: 7
The value of b: 2
现在,让我们了解以上程序。
func()类Example中的成员函数已重载。func()可以根据需要选择具有不同参数的3个功能。给出的代码片段如下。class Example {
public :
void func(int a) {
cout <
}
void func(int a, int b) {
cout <
cout <
}
void func(char c) {
cout <
}
};
在函数中main(),创建了Example类的对象obj。func()使用不同的参数调用该函数以演示函数重载。给出的代码片段如下。int main() {
Example obj;
cout<
obj.func(5);
cout<
obj.func('A');
cout<
obj.func(7, 2);
return 0;
}