2012-02-13 5 views
3

부모 클래스가 있고 그 부모 클래스의 공개 파생 클래스가 2 개 있습니다. 예.다른 파생 클래스에서 파생 클래스의 멤버에 액세스하는 방법?

     class Parent 
         |  | 
         |  | 
         |  | 
       class derived1 class derived2. 

질문 : 내가 다른 파생 클래스에서 하나 개의 파생 클래스의 private 멤버에 액세스하고 싶습니다. 어떻게해야합니까?

내가 가진 방법은 다음과 같습니다. cDerived1 개체를 매개 변수로 cDerived2의 ctor에 전달합니다. 나는 이런 식으로 할 경우, 내가 cDerived1의 친구로 cDerived2를 선언해야하고 또한 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); 
} 

이 그것을 할 수 또는 내가 아주 노골적으로 일을하고있는 올바른 방법인가 잘못된 ??

감사합니다.

Paul의 의견에 대한 답변 : 이미 아래에 표시된 것처럼 부모 클래스에 공유 코드가 있습니다.

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 ? 
+0

깨끗한 방법은 공유 클래스를 부모 클래스로 푸시하는 것입니다. 그렇지 않다면, 메소드를 public으로 만들거나 친구 구문을 사용하시오. –

+0

'pArr'가베이스에 있다면, 그냥 기본 포인터를 물어볼 수 없습니까? –

답변

0

이것은 friend 키워드가 사용 된 것입니다. 함수 나 클래스 중 하나에 사용할 수 있습니다.이 경우 클래스에 적용합니다. 보호 된 멤버에 액세스 할 수있는 유일한 방법은 상속을 사용하는 것입니다. 하위 클래스 또는 친구 클래스에 속합니다. 클래스 외부의 비공개 멤버에 액세스하는 유일한 방법은 친구 함수 또는 클래스를 사용하는 것입니다. 다음은 관련 링크입니다 cplusplus.com

다음은 친구 클래스 선언의 예입니다 (두 번째).

friend class Derived1; // place in Derived2 

friend class Derived2; // place in Derived1 

파생 (1) 파생 2 개 개인 회원에 액세스 할 것이며, 파생 1 개 개인 회원에 액세스 할 수있는 것이 유래 :

class CSquare { 
    private: 
    int side; 
    public: 
    void set_side (int a) 
     {side=a;} 
    friend class CRectangle; // here is the friend declaration 
}; 

그래서 귀하의 예제에서 당신은 사용할 수 있습니다.

간단히 게터 기능을 사용하고 싶지 않다고 가정합니다. 이 친구를 선언되면

당신은 사용할 수 있습니다

Obj.theVar

대신이 같은 getter 함수를 사용하여 :

Obj.getVar()

0

파가 기본 클래스에 있기 때문에, cDerived1의 정의없이이 작업을 수행 할 수 있습니다. cDerived1의 객체를 cparent 클래스의 포인터로 전달하면 모든 것이 정상적으로 처리됩니다. 다음은 몇 가지 샘플 코드입니다 ...

// 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 ? 
void AccessPArr(cparent* pParent) 
{ 
// access over here 
} 

int main() 
{ 
cDerived1 der1; 
cDerived2 der2; 

der2.AccessPArr(&der1); 
} 
관련 문제