访问派生类C ++的私有成员 [英] Accessing private members of a derived class C++

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

问题描述

我试图通过基类的对象访问派生类的私有成员.这是我想做的事情:

I am trying to access derived class' private members via an object of the base class. Here is what I'm trying to do :

 class A {

      private:

           int a, b;

      public:
           A(_a, _b) : a(_a), b(_b) {}
           int getA() { return a; }
           int getB() { return b; }
 };

 class B : public A {

      private:
           int c;

      public:
           B(_a, _b, _c) : A(_a, _b), c(_c) {}
           int getC() { return c; }

 };

 vector<A*> objects;
 A* retVal = new B(1,2,3);
 objects.push_back(retVal);

现在怎么可能访问它?

 objects[0] -> getC();

我有点困惑.

谢谢.

推荐答案

如果您知道对象实际上是派生类型B,则可以执行以下操作:

If you know the object is actually of derived type B, you can do this:

static_cast<B*>(objects[0])->getC();

如果您错了,并且该对象实际上不是B类型(或B的子类),则您的程序将调用未定义的行为,所以不要这样做.

If you are wrong and the object is not actually of type B (or a subclass of B), your program will invoke undefined behavior, so don't do that.

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

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