通过指针访问虚拟类

Accessing virtual class through the pointer

本文关键字:虚拟 访问 指针      更新时间:2023-10-16

我必须设计项目的特定架构。我在尝试创建指向虚拟类的指针时卡住了,并遇到了分段错误(似乎我的指针分配不正确(。下面我包括了我正在尝试做的事情的草稿。

// 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.
}

怎样才能在这三者之间建立联系,这样我才能得到我想要的结果。我不能改变架构,或者简单地省略任何类 A、B 或 C。感谢您的帮助!

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

因此,在 C 类中,您可以有类似以下内容:

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

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

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