// This program has a subtle error in the virtual functions. #include <iostream> #include <memory> using namespace std; class Base { public: virtual void functionA(int arg) const{cout << "This is Base::functionA" << endl; } }; class Derived : public Base { public: virtual void functionA(long arg) const{ cout << "This is Derived::functionA" << endl; } }; int main() { // Base pointer b points to a Derived class object. shared_ptr<Base>b = make_shared<Derived>(); // Call virtual functionA through Base pointer. b->functionA(99); return 0; }程式輸出結果:
This is Base::functionA
在該程式中,Base 類指標 b 指向 Derived 類物件。因為 functionA 是一個虛擬函式,所以一般可以認為 b 對 functionA 的呼叫將選擇 Derived 類的版本。//This program demonstrates the use of the override keyword. #include <iostream> #include <memory> using namespace std; class Base { public: virtual void functionA(int arg) const { cout << "This is Base::functionA" << endl;} }; class Derived : public Base { public: virtual void functionA(int arg) const override{ cout << "This is Derived::functionA" << endl; } }; int main() { // Base pointer b points to a Derived class object. shared_ptr<Base>b = make_shared<Derived>(); // Call virtual functionA through Base pointer. b->functionA(99); return 0; }程式輸出結果:
This is Derived::functionA