C++ 有没有一种方法可以通过指向基类的指针访问所有级别的继承?
给出以下示例:C++ 有没有一种方法可以通过指向基类的指针访问所有级别的继承?,c++,pointers,inheritance,C++,Pointers,Inheritance,给出以下示例: class Base { public: virtual void PrintSomething(); } Base::PrintSomething() { printf("A\n"); } class DerivedOne : public Base { public: void PrintSomething(); } Derived
class Base
{
public:
virtual void PrintSomething();
}
Base::PrintSomething()
{
printf("A\n");
}
class DerivedOne : public Base
{
public:
void PrintSomething();
}
DerivedOne::PrintSomething()
{
printf("B\n");
}
class DerivedTwo : public DerivedOne
{
public:
void PrintSomething();
}
DerivedTwo::PrintSomething()
{
printf("C\n");
}
main()
{
DerivedOne *pOne = new DerivedTwo();
我可以访问每个PrintSomething()
函数
pTwo -> PrintSomething();
pTwo -> DerivedTwo::PrintSomething();
pTwo -> Base::PrintSomething();
Base *pBase = new DerivedTwo();
我只能访问base
和DerivedTwo
函数
pBase -> PrintSomething();
pBase -> Base::PrintSomething();
pBase -> DerivedOne::PrintSomething(); //Error: DerivedOne is not a base of Base
}
如果希望调用
DerivedOne::PrintSomething
,则应使用DerivedOne
指针初始化pBase
。否则你就全做错了。另外,请使用std::unique\u ptr
或任何其他智能指针。我同意Jeffrey的观点
DerivedTwo *pBase = new DerivedTwo();
pBase -> Base::PrintSomething();
pBase -> DerivedOne::PrintSomething();
pBase -> PrintSomething();
这会奏效的
如果您这样做:
Base *pBase = new DerivedTwo();
然后pBase持有DerivedTwo类虚拟表的虚拟指针,因此它可以访问DerivedTwo类的PrintSomething
尽管您可以从DerivedTwo::PrintSomething()函数内部调用DerivedOne::PrintSomething(),如下所示:
void DerivedTwo::PrintSomething()
{
DerivedOne :: PrintSomething();
printf("C\n");
}
从一个指向基类型的指针到不强制转换?简短回答:不。长回答:不。这不是继承和动态多态的工作原理。明白了,谢谢。现在我该如何选择正确的答案呢?这就像试图用派生类指针指向一个基对象一样?是的,我只是在示例中使用了常规指针,以使其更易于阅读(和键入)。我还不需要按我的要求去做。我只是在摆弄课程和学习指南,问题就来了。