3 回答

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊
virtual
class Animal{ public: void eat() { std::cout << "I'm eating generic food."; }};class Cat : public Animal{ public: void eat() { std::cout << "I'm eating a rat."; }};
Animal *animal = new Animal;Cat *cat = new Cat;animal->eat(); // Outputs: "I'm eating generic food."cat->eat(); // Outputs: "I'm eating a rat."
virtual
.
eat()
// This can go at the top of the main.cpp filevoid func(Animal *xyz) { xyz->eat(); }
Animal *animal = new Animal;Cat *cat = new Cat;func(animal); // Outputs: "I'm eating generic food."func(cat); // Outputs: "I'm eating generic food."
func()
func()
Cat*
func()
.
eat()
Animal
class Animal{ public: virtual void eat() { std::cout << "I'm eating generic food."; }};class Cat : public Animal{ public: void eat() { std::cout << "I'm eating a rat."; }};
func(animal); // Outputs: "I'm eating generic food."func(cat); // Outputs: "I'm eating a rat."

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
class Base{ public: void Method1 () { std::cout << "Base::Method1" << std::endl; } virtual void Method2 () { std::cout << "Base::Method2" << std::endl; }};class Derived : public Base{ public: void Method1 () { std::cout << "Derived::Method1" << std::endl; } void Method2 () { std::cout << "Derived::Method2" << std::endl; }};Base* obj = new Derived (); // Note - constructed as Derived, but pointer stored as Base*obj->Method1 (); // Prints "Base::Method1"obj->Method2 (); // Prints "Derived::Method2"
編輯
- 3 回答
- 0 關(guān)注
- 637 瀏覽
添加回答
舉報(bào)