虚函数是一种多态性机制,允许派生类覆盖其基类的成员函数:声明:在函数名前加上关键字 virtual。调用:使用基类指针或引用,编译器将动态绑定到派生类的适当实现。实战案例:通过定义基类 shape 及其派生类 rectangle 和 circle,展示虚函数在多态中的应用,计算面积和绘制形状。

C++ 中的虚函数
虚函数是一种多态性机制,允许派生类覆盖其基类的成员函数。这使程序员能够在基类中定义通用的行为,同时仍然允许派生类为该行为提供特定于其实例的实现。
声明虚函数
立即学习“C++免费学习笔记(深入)”;
要声明一个虚函数,请在函数名的开头放置关键字 virtual。例如:
class Base {
public:
virtual void print() const;
};调用虚函数
调用虚函数,使用基类指针或引用。编译器将动态绑定到派生类的适当实现。例如:
void doSomething(Base* base) {
base->print();
}实战案例
下面是一个使用虚函数的示例:
#include <iostream>
class Shape {
public:
virtual double area() const = 0;
virtual void draw() const = 0;
};
class Rectangle : public Shape {
public:
Rectangle(double width, double height) : width_(width), height_(height) {}
double area() const override { return width_ * height_; }
void draw() const override { std::cout << "Drawing rectangle" << std::endl; }
private:
double width_;
double height_;
};
class Circle : public Shape {
public:
Circle(double radius) : radius_(radius) {}
double area() const override { return 3.14 * radius_ * radius_; }
void draw() const override { std::cout << "Drawing circle" << std::endl; }
private:
double radius_;
};
int main() {
Shape* rectangle = new Rectangle(5, 10);
Shape* circle = new Circle(5);
std::cout << rectangle->area() << std::endl; // Output: 50
std::cout << circle->area() << std::endl; // Output: 78.5
rectangle->draw(); // Output: Drawing rectangle
circle->draw(); // Output: Drawing circle
return 0;
}以上就是C++ 中如何声明和调用虚函数?的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号