从基类的指针访问派生类的成员 [英] Access member of derived class from pointer of base class

查看:72
本文介绍了从基类的指针访问派生类的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个派生自另一个类的类,我使用一个基类指针数组来保存派生类的实例,但是由于该数组属于基类,所以无法使用指针访问属于派生类的成员表示法,是否可以用一个简单的命令访问这些成员,还是应该重写基类以定义该成员并仅在派生类中使用它?

I have a class that is derived from another, I use an array of base class pointers to hold instances of the derived class, but because the array is of the base class, I cannot access members belonging to the derived class with pointer notation, is it possible for me to access these members with a simple command or should I just rewrite my base class to define the member and only use it in the derived class?

示例:

class A {
public:
    int foo;
};

class B : public A {
public:
    char bar;
};

class C : public A {
    int tea;
};

int main() {
    A * arr[5];
    arr[0] = new B;

    char test = arr[0]->bar; //visual studio highlights this with an error "class A has no member bar"

    return 0;
}

推荐答案

我无法使用指针符号访问属于派生类的成员

I cannot access members belonging to the derived class with pointer notation

这是设计使然:您没有告诉编译器指针所指向的对象属于派生类型.

This is by design: you did not tell the compiler that the object pointed to by the pointer is of the derived type.

我是否可以通过简单的命令访问这些成员

is it possible for me to access these members with a simple command

如果您100%确定指针指向 B ,则可以执行 static_cast< B *>(arr [0])浇铸溶液应作为最后的手段.相反,您应该在基类中派生一个成员函数,并在派生类中提供一个实现:

You can do it if you perform static_cast<B*>(arr[0]) if you are 100% certain that the pointer points to B, but casting solution should be used as the last resort. Instead, you should derive a member function in the base class, and provide an implementation in the derived class:

class A {
public:
    int foo;
    virtual char get_bar() = 0;
};

class B : public A {
    char bar;
public:
    char get_bar() {
        return bar;
    }
};

这篇关于从基类的指针访问派生类的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆