Polymorphism in C++

后端 未结 7 883
甜味超标
甜味超标 2020-11-22 09:01

AFAIK:

C++ provides three different types of polymorphism.

  • Virtual functions
  • Function name overloading
  • Operator overloading
7条回答
  •  长情又很酷
    2020-11-22 09:32

    Here is a basic example using Polymorphic classes

    #include 
    
    class Animal{
    public:
       Animal(const char* Name) : name_(Name){/* Add any method you would like to perform here*/
        virtual void Speak(){
            std::cout << "I am an animal called " << name_ << std::endl;
        }
        const char* name_;
    };
    
    class Dog : public Animal{
    public:
        Dog(const char* Name) : Animal(Name) {/*...*/}
        void Speak(){
            std::cout << "I am a dog called " << name_ << std::endl;
        }
    };
    
    int main(void){
        Animal Bob("Bob");
        Dog Steve("Steve");
        Bob.Speak();
        Steve.Speak();
        //return (0);
    }
    

提交回复
热议问题