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"
}
我的问题是,当我有一个指向子类(“b”)对象的基类(“a”)指针时,如何访问“obj”成员?我知道转换应该可以解决问题,但我正在寻找更好的解决方案。
最佳答案
您可以使用 dynamic_cast<>
运算符将指针转换为 a
指向 b
的指针.仅当 ptr
指向的对象的运行时类型时,转换才会成功。是b
, 否则将返回一个空指针,所以你必须在转换后检查结果:
b* p = dynamic_cast<b*>(ptr);
if (p != nullptr)
{
// It is safe to dereference p
p->foo();
}
如果你能保证ptr
指向的对象的类型是b
,但是,在这种情况下(因为不涉及虚拟继承)您甚至可以使用 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();
关于c++ - 使用指向基抽象类的指针访问子类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14820541/