我有以下类层次结构:
class A
{
public:
virtual void func()
{
cout<<"A"<<endl;
}
};
class B: public A
{};
class C: public B
{
public:
virtual void func()
{
cout<<"C"<<endl;
}
};
class D: public C
{
public:
virtual void func()
{
//I don't want to use the class C's implementation
//So I should call the next base function: B::func()
//But since B does not re-define the virtual function, we might as well
//directly call A::func()
//But what is the correct practice? Call A::func() directly or call B::func()
//A::func();
//B::func();
}
};
int main()
{
A *ob;
D dob;
ob = &dob; ob->func();
return 0;
}
我不想使用C类的实施 所以我应该调用下一个基函数:B :: func() 但由于B不重新定义虚函数,我们不妨直接调用A :: func() 但正确的做法是什么?直接调用A :: func()或调用B :: func()
答案 0 :(得分:1)
没有真正的差异,因为B结构包含A::func()
本身的副本 - 当派生不覆盖父类实现时,将复制该函数。但是,我相信将C对象再次从B转回A将效率较低,因此我认为B::func()
是两者中较好的方法。