继承中的不同类型函数详解
在C++的继承中,有三种不同类型的函数:普通函数、虚函数和纯虚函数。这些函数的实现方式不同,各自有着特定的作用和用途。本篇文章将对这三种函数进行详细讲解,以便读者更好地理解C++继承机制。
【普通函数】
普通函数在C++中使用最为广泛,它们是一种非虚函数,也就是说,它们不会被子类所覆盖。因此,在子类中调用该函数时,会直接调用基类中的实现。这种函数可以直接继承或者重载,在派生类中使用与基类中相同的名称和参数列表进行定义。具体示例如下:
#include <iostream>
using namespace std;
class Base {
public:
void func() { cout << "Base::func() called." << endl; }
};
class Derived : public Base {
public:
// 重载
void func(int i) { cout << "Derived::func(int) called." << endl; }
};
int main() {
Base b;
Derived d;
b.func(); // Base::func() called.
d.func(); // Base::fun