C++基础-虚方法
            
            
                    
                        标签:rtu   使用   ace   int   style   ret   执行   dog   protected   
当在子类中对基类的方法进行覆盖时,使用Pet *cat = new Cat("加菲") 进行变量声明时,调用覆盖的函数,为了执行更快C++优先读取基类的方法,因此在基类声明时,需要将其方法声明为虚方法
#include 
#include string>
using namespace std;
class Pet
{
public:
    Pet(string theName);
    void eat();
    void sleep();
    virtual void play(); //被子类覆盖的方法
protected:
    string name;
};
class Cat : public Pet
{
public:
    Cat(string theName);
    void climb();
    void play();
};
class Dog :public Pet
{
public:
    Dog(string theName);
    void bark();
    void play();
};
Pet::Pet(string theName){
    name = theName;
}
void Pet::eat() {
    cout "正在吃东西\n";
}
void Pet::sleep() {
    cout "正在睡觉\n";
}
void Pet::play() {
    cout "正在玩儿\n";
}
Cat::Cat(string theName) : Pet(theName){
}
void Cat::climb() {
    cout "正在爬树\n";
}
void Cat::play() {
    Pet::play();
    cout "玩毛线球\n";
}
Dog::Dog(string theName) : Pet(theName){
}
void Dog::bark() {
    cout "旺 旺\n";
}
void Dog::play() {
    Pet::play();
    cout "正在追赶该死的猫\n";
}
int main() {
    Pet *cat = new Cat("加菲");
    Pet *dog = new Dog("欧迪");
    cat->sleep();
    cat->eat();
    cat->play();
    dog->sleep();
    dog->eat();
    dog->play();
    delete cat;
    delete dog;
    return 0; 
}
 
 
C++基础-虚方法
标签:rtu   使用   ace   int   style   ret   执行   dog   protected   
原文地址:https://www.cnblogs.com/my-love-is-python/p/13363982.html
                    
             
            
            
            
            
                
                    文章来自:
搜素材网的
编程语言模块,转载请注明文章出处。
                    文章标题:
C++基础-虚方法
                    文章链接:http://soscw.com/index.php/essay/74001.html                
 
            
                                
评论