C++ 重载, 重定义, 重写
作者:野牛程序员:2024-01-03 20:19:22 C++阅读 2665
C++中,重载(Overloading)、重定义(Override)和重写(Overriding)是面向对象编程的重要概念。
重载是指在同一个作用域内,可以定义多个同名的函数或运算符,但它们的参数类型或个数必须不同。编译器通过参数列表的不同来区分这些重载的函数或运算符,从而允许在程序中使用相同的名称进行多种操作。
重定义通常用于派生类(子类)中,它指的是在派生类中重新定义基类(父类)中已经存在的成员函数。在重定义时,函数的签名(包括参数类型和个数)必须与基类中的原始函数相匹配。这样,通过基类指针或引用调用该函数时,根据实际对象类型的不同,会调用相应派生类中的函数。
重写也发生在派生类中,但它强调的是通过在派生类中提供新的实现来覆盖基类中的虚函数。重写通常涉及到使用关键字override
,以确保子类中的函数与基类中的虚函数具有相同的签名。这样,通过基类指针或引用调用虚函数时,会根据实际对象类型调用相应派生类中的实现。
总的来说,重载是在同一作用域内使用相同名称但不同参数的多个函数或运算符,重定义是在派生类中重新定义基类中的成员函数,而重写是通过在派生类中提供新的实现来覆盖基类中的虚函数。
重载(Overloading)的例子:
#include <iostream> class MathOperations { public: int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } }; int main() { MathOperations math; std::cout << "Sum of integers: " << math.add(5, 3) << std::endl; std::cout << "Sum of doubles: " << math.add(2.5, 3.7) << std::endl; return 0; }
重定义(Override)的例子:
#include <iostream> class Base { public: void display() { std::cout << "Base class display()" << std::endl; } }; class Derived : public Base { public: void display() { std::cout << "Derived class display()" << std::endl; } }; int main() { Derived derivedObj; derivedObj.display(); // Calls the overridden function in the Derived class return 0; }
重写(Overriding)的例子:
#include <iostream> class Shape { public: virtual void draw() { std::cout << "Drawing a shape" << std::endl; } }; class Circle : public Shape { public: void draw() override { std::cout << "Drawing a circle" << std::endl; } }; int main() { Shape* shapePtr = new Circle(); shapePtr->draw(); // Calls the overridden function in the Circle class delete shapePtr; return 0; }
请注意,在重写的例子中,基类的虚函数需要使用关键字 virtual
声明,而派生类中的对应函数则使用 override
关键字来确保正确的重写。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:C/C++const修饰指针变量的情况
- 下一篇:C++ 虚表和多态的实现原理