C++ 中指向对象和后代的指针

pointers to object and descendants in C++

我正在开发一个简单的 C++(在 Linux 下)项目,该项目将包含指向对象的指针。我有 class A,class B 扩展了 A,class C 扩展了 B。Class C 有一个方法(测试)在 A 或 B 中不存在.

是否可以有一个指针 'p' 可以指向 A、B 和 C 类型的对象?我将如何定义该指针?

其次,由于 a.test() 不存在,但 c.test() 存在,我的通用指针 'p' 可以调用 p->test() 吗?这会编译吗?如果在 运行 时间 p 指向 class A 的对象并且我调用 p->test() 怎么办?这是 运行 时间错误吗?

Is is possible to have a single pointer that can point to an object of type A, B, and C ?

我假设你的意思是 "that can either point to an A object or to B object or to a C object",对吧?

是的,你可以有这样的指针。

How would I define that pointer?

A*

基class指针可以指向派生classes的对象。

Secondly, how would I call methods of the object if the pointer can point to A/B/C classes?

您在 A 中定义了一个 virtual 函数,并在 BC 中覆盖了它。然后,当你通过你的 A* 调用该方法时,语言将执行动态调度,即它会根据你的 A* 是否指向一个 A、指向一个BC.

Do I need to cast them before calling the methods?

没有。这几乎会破坏虚函数的目的。

这是一个完整的例子:

#include <iostream>

class A
{
public:
    virtual ~A() {} // not really needed in this program,
                    // but almost always needed in real code
                    // when a class has a virtual function
    virtual void method() { std::cout << "A::method\n"; }
};

class B : public A
{
public:
    virtual void method() override { std::cout << "B::method\n"; }
};

class C : public A
{
public:
    virtual void method() override { std::cout << "C::method\n"; }
};

int main()
{
    A a;
    B b;
    C c;
    A* ptr = &a;
    ptr->method();
    ptr = &b;
    ptr->method();
    ptr = &c;
    ptr->method();
}

输出:

A::method
B::method
C::method