我有一个父类,我有 2 个从该父类公开派生的类。例如。
class Parent
| |
| |
| |
class derived1 class derived2.
问题:我想从另一个派生类访问一个派生类的私有成员。我该怎么做呢?
我现在的方法如下:将cDerived1对象作为参数传递给cDerived2的ctor。如果我这样做,那么我必须将 cDerived2 声明为 cDerived1 的朋友,并在 cDerived2.h 中包含 cDerived1.h
#include cParent.h
#include cDerived1.h
#include cDerived2.h
void main (){
// Instantiate a cDerived1 object
Derived1 dev1();
// Instantiate a cDerived2 object. The cDerived2 object will need access to the
// private members of cDerived1. So pass dev1 by reference to dev2 ctor.
Derived2 dev2(dev1);
}
这是正确的做法还是我做错了什么?
谢谢。
回应保罗的评论:我已经在父类中有共享代码,如下所示。
cParent.h
class cparent{
public:
// ctor
// dtor
protected:
int* pArr;
};
cDerived1.h
// derived1's header
#include "cParent.h"
class cDerived1 : public cParent{
public:
//
};
cDerived2.h
// derived2's header
#include "cParent.h"
class cDerived2 : public cParent{
public:
// I want access to derived1's pArr member over here....How do I do this ?