
C 语言面向对象编程:继承中的虚函数与多态性的妙用
虚函数
虚函数是一种在派生类中重写基类方法的方法,允许在运行时动态绑定。当调用虚函数时,将根据对象的实际类型调用其对应的实现。
声明虚函数
立即学习“C语言免费学习笔记(深入)”;
要在基类中声明虚函数,请在方法声明中使用 virtual 关键字,如下所示:
class Base {
public:
virtual void print() { cout << "Base class print" << endl; }
};重写虚函数
在派生类中重写虚函数,只需在派生类方法声明中覆盖基类的方法即可:
class Derived : public Base {
public:
virtual void print() override { cout << "Derived class print" << endl; }
};多态性
多态性是指对象能够以与实际类型不同的方式表现的行为。通过虚函数,我们可以创建父类指针或引用,并指向派生类对象。当通过父类指针或引用调用虚函数时,将调用派生类的实现。
实战案例
以下代码演示了虚函数和多态性的用法:
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() {} // 虚函数
virtual double getArea() { return 0.0; } // 虚函数
};
class Rectangle : public Shape {
public:
Rectangle(double width, double height) : _width(width), _height(height) {}
void draw() override { cout << "Drawing a rectangle" << endl; }
double getArea() override { return _width * _height; }
private:
double _width, _height;
};
class Circle : public Shape {
public:
Circle(double radius) : _radius(radius) {}
void draw() override { cout << "Drawing a circle" << endl; }
double getArea() override { return 3.14 * _radius * _radius; }
private:
double _radius;
};
int main() {
Shape* shapes[] = { new Rectangle(4, 5), new Circle(3) };
for (Shape* shape : shapes) {
shape->draw();
cout << "Area: " << shape->getArea() << endl;
}
return 0;
}输出:
Drawing a rectangle Area: 20 Drawing a circle Area: 28.26
以上就是C语言面向对象编程:继承中的虚函数与多态性的妙用问答的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号