简体   繁体   English

带有继承的编译器行为

[英]Compiler behavior with inheritance

I have a question about the compiler behavior when I use up-casting in C++. 我在C ++中使用向上转换时有关于编译器行为的问题。 For example I have this simple code: 例如,我有这个简单的代码:

class Animal {

public:
    Animal() {}

    void talk() {
        std::cout << "I am an animal" << std::endl;
    }
};

class Dog :public Animal {

public:
    Dog(){}

    void talk() {
        std::cout << "I am a dog" << std::endl;
    }

    void eat() {
        std::cout << "eating" << std::endl;
    }
}; 

int main()
{
    Animal* animal = new Dog();
    animal->talk();//Output is "I am an animal"
    //animal->eat();//Compilation error.
    return 0;
}

My question is, where does the compiler go first when I run this? 我的问题是,运行此命令时,编译器首先在哪里运行? Does it look for the methods in Animal class, and then because I didn't use virtual it calls for the Animal's talk() method, or does it checks if the method exists in the Dog class first, and calls for the Animal's method? 它是在Animal类中查找方法,然后因为我没有使用虚拟方法而调用动物的talk()方法,还是先检查该方法是否存在于Dog类中,然后再调用Animal的方法?

Given your code, animal->talk() will always call Animal::talk() . 给定您的代码, animal->talk()将始终调用Animal::talk() Because animal is a Animal * and Animal::talk() is not virtual. 因为animalAnimal *Animal::talk()不是虚拟的。

Now if you make Animal::talk() virtual, animal->talk() will call Dog::talk() . 现在,如果您将Animal::talk()虚拟,则animal->talk()将调用Dog::talk() Normally this is done by looking at run-time at the vtable of animal to see the real type of the object and then call the most appropriate talk() function. 通常,这是通过在animal的vtable上查看运行时以查看对象的真实类型,然后调用最合适的talk()函数来完成的。 But since you have Animal *animal = new Dog() just above, the compiler can choose to optimize the call by skipping the vtable lookup and make a direct call to Dog::talk() as the type is already known at compile time. 但是由于上面有Animal *animal = new Dog() ,因此编译器可以选择跳过vtable查找来优化调用,并直接调用Dog::talk()因为该类型在编译时已为人所知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM