C++中的多态性
多态性 意味着有多种形式。通常,当类有层次结构并且它们通过继承相关时,就会发生多态性。
C++ 多态性意味着对成员函数的调用将导致执行不同的函数,具体取决于调用该函数的对象的类型。
考虑以下示例,其中一个基类已由其他两个类派生 -
现场演示
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape {
public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// Main function for the program
int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// store the address of Rectangle
shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();
return 0;
}
当上面的代码编译并执行时,它会产生以下结果 -
Parent class area : Parent class area :
错误输出的原因是函数 area() 的调用被编译器设置为基类中定义的版本。这称为静态分辨率 函数调用或静态链接 - 在程序执行之前,函数调用是固定的。这有时也称为早期绑定 因为area()函数是在程序编译的时候设置的。
但是现在,让我们对我们的程序稍作修改,在 Shape 类中声明 area() 之前加上关键字 virtual 所以它看起来像这样 -
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
经过这个轻微的修改,当前面的示例代码被编译和执行时,它会产生以下结果 -
Rectangle class area Triangle class area
这一次,编译器查看指针的内容而不是类型。因此,由于 tri 和 rec 类的对象的地址存储在 *shape 中,因此调用了各自的 area() 函数。
如您所见,每个子类都有单独的函数 area() 实现。这就是多态性 一般使用。您有不同的类,具有相同名称的函数,甚至相同的参数,但实现不同。
虚函数
一个虚拟 function 是使用关键字 virtual 声明的基类中的函数 .在基类中定义一个虚函数,在派生类中定义另一个版本,向编译器发出信号,我们不希望该函数使用静态链接。
我们想要的是在程序中的任何给定点选择要调用的函数,以基于调用它的对象的类型。这种操作称为动态链接 , 或后期绑定 .
纯虚函数
您可能希望在基类中包含一个虚函数,以便可以在派生类中重新定义它以适应该类的对象,但是对于基类中的函数没有有意义的定义.
我们可以将基类中的虚函数 area() 更改为以下内容 -
class Shape {
protected:
int width, height;
public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}
// pure virtual function
virtual int area() = 0;
};
=0 告诉编译器该函数没有主体,上面的虚函数将被称为纯虚函数 .
C语言