C++ 虚函数
跳到导航
跳到搜索
虚函数是应在派生类中重新定义的成员函数。 当使用指针或对基类的引用来引用派生的类对象时,可以为该对象调用虚函数并执行该函数的派生类版本。
如果声明的类不提供 PrintBalance 函数的重写实现,则使用基类 Account 中的默认实现。
可通过使用范围解析运算符 (::) 显式限定函数名称来禁用虚函数调用机制。
#include <iostream> using namespace std; class Base { public: virtual void NameOf(); // Virtual function. void InvokingClass(); // Nonvirtual function. }; // Implement the two functions. void Base::NameOf() { cout << "Base::NameOf\n"; } void Base::InvokingClass() { cout << "Invoked by Base\n"; } class Derived : public Base { public: void NameOf(); // Virtual function. void InvokingClass(); // Nonvirtual function. }; // Implement the two functions. void Derived::NameOf() { cout << "Derived::NameOf\n"; } void Derived::InvokingClass() { cout << "Invoked by Derived\n"; } int main() { // Declare an object of type Derived. Derived aDerived; // Declare two pointers, one of type Derived * and the other // of type Base *, and initialize them to point to aDerived. Derived* pDerived = &aDerived; Base* pBase = &aDerived; // Call the functions. pBase->NameOf(); // Call virtual function. pBase->InvokingClass(); // Call nonvirtual function. pBase->Base::NameOf(); pDerived->NameOf(); // Call virtual function. pDerived->InvokingClass(); // Call nonvirtual function. }
Derived::NameOf Invoked by Base Base::NameOf Derived::NameOf Invoked by Derived