通过指针访问虚拟class

Accessing virtual class through the pointer

我要设计项目的具体架构。我在尝试创建指向虚拟 class 的指针时卡住了,并遇到了分段错误(似乎我的指针分配不正确)。 下面是我正在尝试做的事情的草稿。

// Class A has to be pure virtual. It will be inherited by many classes in my project.
class A: 
{
public:
 virtual void myFunction() = 0; 
}


// Class B implements the method from the class A
#include <A.h>
class B: public A
{
public:
void myFunction(); // IS IMPLEMENTED HERE!!
}


// Class C creates a pointer to the class A.
 #include <A.h>
class C:
{
A *ptr;
ptr->myFunction();  //Here I want to run myFuction() from the class B.
}

如何在这三者之间建立联系,以便得到我想要的结果。 我无法更改架构,或者只是省略任何 classes A、B 或 C。 感谢您的帮助!

虚拟调用允许通过指针或基类型引用从对象访问函数。请注意,对象本身需要是实现功能的类型。

所以,在 class C 中你可以有这样的东西:

B b;
A *ptr = &b;
ptr->myFunction()

A *ptr = new B();
ptr->myFunction()

无论哪种方式,您都需要创建一个 B 类型的对象,并将其赋值给一个 A* 类型的指针。