使用指向基本abstact类的指针访问子类成员

use*_*947 5 c++ oop inheritance pointers class

class a //my base abstract class
{
public:
virtual void foo() = 0;
};

class b : public a //my child class with new member object
{
public:
void foo()
{}
int obj;
};

int main()
{
b bee;
a * ptr = &bee;
ptr->obj; //ERROR: class a has no member named "obj"
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我有一个指向子类("a")指向子类("b")对象的指针时,如何访问"obj"成员?我知道铸造应该成功,但我正在寻找更好的解决方案.

And*_*owl 7

您可以使用dynamic_cast<>运算符将指针转换为指向a的指针b.仅当指向的对象的运行时类型ptrb,并且将返回空指针时,转换才会成功,因此您必须在转换后检查结果:

b* p = dynamic_cast<b*>(ptr);
if (p != nullptr)
{
    // It is safe to dereference p
    p->foo();
}
Run Code Online (Sandbox Code Playgroud)

但是,如果可以保证所指向的对象的类型ptrb在这种情况下(因为不涉及虚拟继承),您甚至可以使用a static_cast<>,这会产生较少的开销,因为它是在编译时执行的.

b* p = static_cast<b*>(ptr);
// You are assuming ptr points to an instance of b. If your assumption is
// correct, dereferencing p is safe
p->foo();
Run Code Online (Sandbox Code Playgroud)