通过指针访问虚拟类
Accessing virtual class through the pointer
我必须设计项目的特定架构。我在尝试创建指向虚拟类的指针时卡住了,并遇到了分段错误(似乎我的指针分配不正确(。下面我包括了我正在尝试做的事情的草稿。
// 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* 类型的指针。
相关文章:
- 链接器找不到在虚拟类 c++ 中访问的静态字段的符号
- 跨 DLL 边界访问虚拟方法是否安全/可能?
- 从纯虚拟类 (A) 派生的指针无法访问来自纯类 (B) 的重载方法
- 使(虚拟)函数在大多数派生类中无法访问中间基类中可访问,定义良好?
- 当键是虚拟继承中涉及的基类指针时,对 std::unordered_map 项的访问崩溃
- C++ 不明确访问 - 虚拟继承
- C++继承从基类指针访问派生类中的非虚拟函数
- 重写另一个类中的虚拟方法以在 C++ 中访问其成员
- 从两个不同类继承的非虚拟基类的访问成员
- 为什么基指针可以访问虚拟函数中的派生成员变量
- 可编程访问正确的虚拟班级儿童
- 通过在基类中虚拟调用派生类中的函数来访问派生类中的函数
- 通过指针访问虚拟类
- 为什么我可以访问已删除但在C++中具有虚拟析构函数的对象?
- 确定范围是访问虚拟功能的合法方式吗?
- C++11 纯虚拟类的朋友无法访问私有方法
- 我明白为什么,但是虚拟函数/VTable 究竟如何允许通过指针访问正确的函数?
- 访问C 中的Overriden Parent虚拟方法
- 虚拟继承和受保护的成员访问
- 使用虚拟函数访问私有函数