019--C++养成之路(多态:虚函数)

    科技2022-07-11  96

    笔记:关键字virtual(文档说明后续更新,先记录关键代码仅供参考学习)

    没使用virtual:

    #include<iostream> #include<string> using namespace std; class Animal{ public: string m_name; Animal(string name); void say(); }; Animal::Animal(string name):m_name(name){ } void Animal::say(){ cout<<m_name<<":"<<"@#$%%^^"<<endl; } class Dog:public Animal{ public: Dog(string name); void say(); }; Dog::Dog(string name):Animal(name){ } void Dog::say(){ cout<<m_name<<":"<<"one one one......"<<endl; } int main(){ Animal a("动物"); a.say(); Animal* a1=new Dog("狗狗"); a1->say(); getchar(); return 0; }

    运行结果:

    使用虚函数virtual:

    #include<iostream> #include<string> using namespace std; class Animal{ public: string m_name; Animal(string name); virtual void say(); }; Animal::Animal(string name):m_name(name){ } void Animal::say(){ cout<<m_name<<":"<<"@#$%%^^"<<endl; } class Dog:public Animal{ public: Dog(string name); void say(); }; Dog::Dog(string name):Animal(name){ } void Dog::say(){ cout<<m_name<<":"<<"one one one......"<<endl; } int main(){ Animal a("动物"); a.say(); Animal* a1=new Dog("狗狗"); a1->say(); getchar(); return 0; }

    运行结果:

     

    Processed: 0.016, SQL: 8