主页
C++
C++ 虚函数
demo_virtual
运行 ❯
×
更改方向
保存代码
更改主题
#include
using namespace std; class Animal { public: void sound() { cout << "Animal sound\n"; } }; class Dog : public Animal { public: void sound() { cout << "Dog barks\n"; } }; int main() { Animal* a; // Declare a pointer to the base class (Animal) Dog d; // Create an object of the derived class (Dog) a = &d; // Point the base class pointer to the Dog object a->sound(); // Call the sound() function using the pointer. Since sound() is not virtual, this calls Animal's version return 0; }
Animal sound