我无法弄清楚如何为多重继承创建虚函数表的模式。请看以下代码。
// Iam just providing pseudocode model
class A{
public:
Vptr[]; // create function pointer
virtual void run(){}
A(){
this->Vptr[0] = &A::run; // push virtual function address
}
}
class B{
public:
Vptr[]; // create function pointer
virtual void sleep(){}
B(){
this->Vptr[0] = &B::sleep; // push virtual function address
}
}
class C : public A, public B{
public:
virtual void run(){}
virtual void eat(){}
C(){
this->A::Vptr[0] = &C::run; // update function address since overrided
// the question is onto which Vptr does eat() entry is stored?
// this->A::Vptr[1] = &C::eat() OR this->B::Vptr[1] = &C::eat()
}
}
在单继承层次结构中,它会将虚函数条目添加到同一个
VPTR
的末尾,但在多重继承中,它如何决定呢?因为它有两个VPTRs
。
this->
语法;直接访问方法和成员(可以节省打字时间)。只有当方法参数和数据成员 名称相同时 ,才需要使用this->
语法来区分。 - Thomas MatthewsVptr
的类型是什么? - Thomas Matthewsrun
和eat
方法没有重载或覆盖,编译器可以进行优化,不使用虚函数表。 - Thomas Matthews