• C++ 运行时多态


    重载虚函数

    #include <iostream>
    #include <thread>
    using namespace std;
    
    class Animal {
        protected: string name;
        public: Animal(string name) {
            cout << "Animal()" << endl;
            this->name = name;
        }
        // public: void greeting() {
        public: virtual void greeting() {          <--- 如果不是虚函数,就不会查询指针指向的函数表,只会调用基类函数
            cout << "I'm the animal, call me '" << this->name << "'." << endl;
        }
    };
    
    class Dog : public Animal {
        public: Dog(string name) : Animal(name) {
            cout << "Dog()" << endl;
        }
        // public: void greeting() override {
        public: void greeting() {
            cout << "I'm the dog, call me '" << this->name << "'." << endl;
        }
    };
    
    class Cat : public Animal {
        public: Cat(string name) : Animal(name) {
            cout << "Cat()" << endl;
        }
        // public: void greeting() override {          <--- 可以使用override关键字明确指定是重载虚函数
        public: void greeting() {
            cout << "I'm the cat, call me '" << this->name << "'." << endl;
        }
    };
    
    int main() {
        Animal *what = new Dog(string("shibainu"));
        what->greeting();
        delete what;
        what = new Cat(string("niaoniao"));
        what->greeting();
        delete what;
        return 0;
    }
    
  • 相关阅读:
    避免前置声明
    CLion在WSL上远程调试代码设置
    push_back与构造函数
    _BLOCK_TYPE_IS_VALID(pHead->nBlockUse问题解析
    Qt报错
    关于引用与指针实现多态的一些记录
    Vue-Axios异步通信
    Kafka概述
    学习Ajax看着一篇就够了
    学习Json看着一篇就够了
  • 原文地址:https://www.cnblogs.com/develon/p/15897451.html
Copyright © 2020-2023  润新知