c++++中,函数重写允许派生类覆盖基类函数,以扩展或修改其行为。其语法为:具有相同函数名具有相同函数签名使用override关键字

C++ 中函数重写的全面指南
在 C++ 中,函数重写允许派生类覆盖基类中的函数。这在扩展基类功能或修改其行为时非常有用。
语法
立即学习“C++免费学习笔记(深入)”;
要覆盖基类函数,派生类中的函数必须:
override 关键字例如,考虑以下基类:
class Base {
public:
virtual void print() { std::cout << "Base class" << std::endl; }
};要覆盖 print() 函数,派生类可以使用以下语法:
class Derived : public Base {
public:
override void print() { std::cout << "Derived class" << std::endl; }
};实战案例
考虑一个 Shape 基类和一个 Circle 派生类:
class Shape {
public:
virtual double area() { return 0; }
};
class Circle : public Shape {
public:
double radius;
override double area() {
return 3.14 * radius * radius;
}
};在 main() 函数中,我们可以使用虚方法调度调用这两个方法:
int main() {
// 创建一个圆形对象
Circle circle;
circle.radius = 5;
// 通过基类指针调用派生类函数
Shape* shape = &circle;
double area = shape->area();
std::cout << "Area of the circle: " << area << std::endl;
return 0;
}输出:
Area of the circle: 78.5
以上就是C++ 中如何覆盖基类函数?的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号