为什么C ++编译器不知道指针指向派生类? [英] Why can't C++ compiler know a pointer is pointing to a derived class?
问题描述
我刚刚开始学习C ++中的OOP.我想知道为什么需要虚拟关键字来指示编译器进行后期绑定?为什么编译器在编译时不知道指针指向派生类?
I've just started learning about OOP in C++. I was wondering why is the virtual keyword needed to instruct the compiler to do late binding ? Why can't the compiler know at compile time that the pointer is pointing to a derived class ?
class A {
public: int f() { return 'A';}
};
class B : public A {
public: int f() { return 'B';}
};
int main() {
A* pa;
B b;
pa = &b;
cout << pa->f() << endl;
}
推荐答案
假设您有一个简单的类层次结构,如
Lets say you have a simple class-hierarchy like
class Animal
{
// Generic animal attributes and properties
};
class Mammal : public Animal
{
// Attributes and properties specific to mammals
};
class Fish : public Animal
{
// Attributes and properties specific to fishes
};
class Cat : public Mammal
{
// Attributes and properties specific to cats
};
class Shark : public Fish
{
// Attributes and properties specific to sharks
};
class Hammerhead : public Shark
{
// Attributes and properties specific to hammerhead sharks
};
[有点long,但是我想让具体的"类彼此远离]
现在可以说我们有一个类似的功能
Now lets say we have a function like
void do_something_with_animals(Animal* animal);
最后让我们调用此函数:
And finally let's call this function:
Fish *my_fish = new Hammerhead;
Mammal* my_cat = new Cat;
do_something_with_animals(my_fish);
do_something_with_animals(my_cat);
现在,如果我们想一想,在do_something_with_animals
函数中,实际上没有办法确切地了解 参数animal
可能指向什么.是Mammal
吗? Fish
?特定的Fish
子类型?
Now if we think a little, in the do_something_with_animals
function there is really no way of knowing exactly what the argument animal
might point to. Is it a Mammal
? A Fish
? A specific Fish
sub-type?
如果在不同的转换单元,其中甚至可能没有Mammal
和Fish
类(或其任何子类)的定义.
This is even harder for the compiler if the do_something_with_animals
function is defined in a different translation unit, where the definition of the Mammal
and Fish
classes (or any of its sub-classes) might not even be available.
这篇关于为什么C ++编译器不知道指针指向派生类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!