|
发表于 2023-6-9 11:11:47
|
显示全部楼层
在C++中,多态性是面向对象编程的一种重要特性,它允许你使用一个统一的接口来处理不同的对象,而这些对象可以选择以自己的方式响应这些接口的调用。
C++提供了两种类型的多态性:编译时多态性(静态)和运行时多态性(动态)。
1. 编译时多态性: 是通过函数重载和运算符重载实现的。这是在编译时决定的,因为在编译时函数调用已经被解析了。
函数重载示例:
- void print(int i) {
- cout << " Here is int " << i << endl;
- }
- void print(double f) {
- cout << " Here is float " << f << endl;
- }
-
复制代码
2. 运行时多态性: 是通过虚函数和继承实现的。这是在运行时决定的,因为在运行时才知道是哪个类的函数被调用。
虚函数示例:
- class Base {
- public:
- virtual void print() {
- cout << "print base class" << endl;
- }
-
- void show() {
- cout << "show base class" << endl;
- }
- };
-
- class Derived:public Base {
- public:
- void print() {
- cout << "print derived class" << endl;
- }
-
- void show() {
- cout << "show derived class" << endl;
- }
- };
-
- int main() {
- Base *baseptr;
- Derived derivedobj;
- baseptr = &derivedobj;
-
- //virtual function, binded at runtime (Runtime polymorphism)
- baseptr->print();
-
- // Non-virtual function, binded at compile time
- baseptr->show();
-
- return 0;
- }
-
复制代码
在这个例子中, print() 函数是虚函数,所以它在运行时解析,打印出"print derived class"。 show() 函数不是虚函数,所以它在编译时解析,打印出"show base class"。
总的来说,多态性是一种强大的工具,它允许你编写更通用、可重用的代码。 |
|