简体   繁体   English

通过基本 class 指针获取派生 class object 的引用

[英]Get a reference of a derived class object through a base class pointer

I have a vector of base class pointers to store different derived classes.我有一个基本 class 指针向量来存储不同的派生类。 I need to access methods/objects that may be present on a derived class, but not on the base class.我需要访问可能存在于派生 class 上的方法/对象,而不是基础 class 上的方法/对象。

I've tried using a function in the form of something like base* getObject(int idx);我尝试使用类似base* getObject(int idx); and then using dynamic_cast , and static_cast from Base* into Derived& , but that doesn't seem to work, as compilation failed.然后使用dynamic_caststatic_castBase*Derived& ,但这似乎不起作用,因为编译失败。

My base class looks something like this:我的基础 class 看起来像这样:

        class Base {
          int a, b;
        public:
          virtual void f1(int) = 0;
          virtual void f2(int, int) = 0;
        };

And my derived classes look something like this:我的派生类看起来像这样:

        class Derived : public Base {
          std::vector <int> myVector;
        public:
          void f1(int ai) override {}
          void f2(int ai, int bi) override {}
          int getFromVector(int idx) { return myVector[idx]; }
        }

The vector that should contain the derived classes looks like this:应该包含派生类的向量如下所示:

        std::vector <Base*> derivedObjects;

What I would like to do, is to get something from the derivedObjects vector, and access, say, getFromVector() .我想做的是从derivedObjects向量中获取一些东西,然后访问getFromVector()

I would agree with Igor Tandetnik that the interface class may need to be designed better.我同意 Igor Tandetnik 的观点,接口 class 可能需要设计得更好。 With the given statement, dynamic_cast can be used, but you must remember that a dynamic cast is a try, which may fail.使用给定的语句,可以使用 dynamic_cast,但您必须记住,动态转换是一次尝试,它可能会失败。 Since you are using a reference of derived class in the case of cast operation failure, you will have to catch the exception and proceed accordingly.由于您在强制转换操作失败的情况下使用派生 class 的引用,因此您必须捕获异常并相应地继续。

For example, if you have Derived1 and Derived2 classes, and you are trying to dynamically cast a Derived1 object to a Derived2 reference, then a bad_cast exception will be thrown.例如,如果您有 Derived1 和 Derived2 类,并且您尝试将 Derived1 object 动态转换为 Derived2 引用,则将引发 bad_cast 异常。 This happens because a reference object cannot be set to null.这是因为参考 object 不能设置为 null。 As an alternative, you can try to cast it to a pointer of derived type and not a reference.作为替代方案,您可以尝试将其强制转换为派生类型的指针而不是引用。 After trying to dynamically cast, you can check if the pointer is null.尝试动态转换后,您可以检查指针是否为 null。

Further reference: http://www.cplusplus.com/doc/tutorial/typecasting/进一步参考: http://www.cplusplus.com/doc/tutorial/typecasting/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM