C++ 函数覆盖

在本教程中,我们将借助示例了解 C++ 中的函数覆盖。

众所周知,继承是 OOP 的一个特性,它允许我们从基类创建派生类。派生类继承了基类的特性。

假设在派生类和基类中定义了相同的函数。现在如果我们使用派生类的对象调用这个函数,派生类的函数就会被执行。

这在 C++ 中称为函数覆盖。派生类中的函数覆盖基类中的函数。

示例 1:C++ 函数覆盖

本示例程序演示了 C++ 继承中的函数覆盖特性。

#include <iostream>
using namespace std;

class Base {
   public:
    void print() {
        cout << "Base Function" << endl;
    }
};

class Derived : public Base {
   public:
    void print() {
        cout << "Derived Function" << endl;
    }
};

int main() {
    Derived derived1;
    derived1.print();
    return 0;
}

输出 s

Derived Function

这里, 在 BaseDerived 类中定义了相同的 print() 函数。

所以,当我们从 Derived 对象 derived1 调用 print(), 来自 Derivedprint() 是覆盖了 Base 中的 print() 函数。

C++ 函数覆盖的工作
C++ 函数覆盖的工作原理

正如我们所见,该函数被覆盖了,因为我们从 Derived 类的对象中调用了该函数。

如果我们从 Base 类的对象调用 print() 函数,该函数就不会被覆盖。

Base base1;
base1.print();

在 C++ 中访问覆盖函数

要访问基类的被派生类重写函数,我们使用范围解析运算符 ::

我们还可以通过使用基类的指针指向派生类的对象,然后从该指针调用函数来访问重写的函数。

示例 2:C++ 访问基类的重写函数

#include <iostream>
using namespace std;

class Base {
   public:
    void print() {
        cout << "Base Function" << endl;
    }
};

class Derived : public Base {
   public:
    void print() {
        cout << "" << endl;
    }
};

int main() {
    Derived derived1, derived2;
    derived1.print();

    // access print() function of the Base class
    derived2.Base::print();

    return 0;
}

输出

Derived Function
Base Function

在这里,这个声明

derived2.Base::print();

访问 Base 类的 print() 函数。

使用派生对象的 C++ 访问覆盖函数
使用派生对象的 C++ 访问覆盖函数

示例 3:C++ 从派生类调用重写函数

#include <iostream>
using namespace std;

class Base {
   public:
    void print() {
        cout << "Base Function" << endl;
    }
};

class Derived : public Base {
   public:
    void print() {
        cout << "Derived Function" << endl;

        // call overridden function
        Base::print();
    }
};

int main() {
    Derived derived1;
    derived1.print();
    return 0;
}

输出

Derived Function
Base Function

在这个程序中,我们在 Derived 类本身内部调用了被覆盖的函数。

class Derived : public Base {
   public:
    void print() {
        cout << "Derived Function" << endl;
        Base::print();
    }
};

注意代码 Base::print(); ,它调用基类中的重写函数。

C++ 的派生类中访问重写函数
C++ 的派生类中访问重写函数

示例 4:使用指针的 C++ 调用覆盖函数

#include <iostream>
using namespace std;

class Base {
   public:
    void print() {
        cout << "Base Function" << endl;
    }
};

class Derived : public Base {
   public:
    void print() {
        cout << "Derived Function" << endl;
    }
};

int main() {
    Derived derived1;

    // pointer of Base type that points to derived1
    Base* ptr = &derived1;

    // call function of Base class using ptr
    ptr->print();

    return 0;
}

输出

Base Function

在这个程序中,我们创建了一个名为 ptrBase 类型指针. 这个指针指向 Derived 对象 derived1.

Base* ptr = &derived1;

当我们调用 print() 函数时,它调用 Base 中被覆盖的函数。

ptr->print();

这是因为即使 ptr 指向一个 Derived 对象,它实际上是一个 Base 类型。因此,它调用 Base 的成员函数。

为了不访问 Base 中被覆盖的函数,我们需要在 Base 类中使用虚函数