2012-03-26 4 views
0

다른 클래스의 다른 클래스에서 getter 함수를 호출하는 방법이 궁금합니다. 예를 들어 내가 지금하고있는 것이 작동하지 않습니다.클래스의 다른 클래스에서 getter 호출

class A{ 
public: 
    friend class B; 
std::string getfirst(){ return b.getfirst();} 
private: 
    B b; 
}; 

class B{ 
public: 
    std::string getfirst(){ 
     return first_; 

    } 
private: 
    std::string first_; 

}; 

B의 getfirst 기능을 호출 할 수 있도록 어떻게 수정합니까?

+2

이 코드는 약간 컴파일되지 않습니다 ... std :: string getfirst() {std :: string getfirst() {'. –

+0

내가 "약간 컴파일"부분을 좋아했다 ;-) –

답변

2

우정을 필요로하지 않습니다.

약 어떨까요?

class B { 
public: 
    std::string get_first() const { return first_; } 
private: 
    std::string first_; 
}; 

class A { 
public: 
    std::string get_first() const { return b.get_first(); } 
private: 
    B b; 
}; 

이제, 클래스 B가 제 클래스 A에 대한 게터를 갖는 것은 대리자 멤버 변수 내지 b 게터있다.

+0

나는 그것을 시도했다. 그리고 나에게 B가 getfirst 멤버를 가지고 있지 않다는 컴파일 에러를 준다. – user798774

+0

타이핑 확인. 내 예제에서는 getter() 대신 get_first()로 getter를 명명했습니다. –

0
class B{ 
    public: 
     std::string getfirst(){ 
      return first_; 
     } 
    private: 
     std::string first_; 
    }; 

    class A : public B{ 
     public: 
     //class A has derived the "getfirst" from B 
     private: 
     // add your stuff here 
    }; 

는 컴파일하지 못했지만, 좋은

당신이 코드는 오류가
0

작동합니다 : std::string getfirst(){B에 두 번 반복된다, 이것은 컴파일 오류가 발생합니다.

또한 B은 (는) A의 비공개 회원에 액세스하려고 시도하지 않으므로 BA 명의 친구로 선언 할 필요가 없습니다. 큰 코드가있는 경우 이것을 무시하십시오.에 친구 선언이 필요합니다.

A에서 사용하기 전에 클래스 B을 정의해야합니다. BA에 액세스하지 않으므로 A의 앞에 정의를 넣을 수 있습니다.

0

이것은

std::string getfirst(){ 
     std::string getfirst(){ 
      return first_;  //cause compilation error 

그것은으로 해결 될 수도 있습니다 정말 이상한입니다 : 내가 골격 만 제공하고

#include <iostream> 
using namespace std; 

class B; // Forward declaration of class B in order for example to compile 
class A 
{ 

public: 

    string getfirst(); 
    friend string :: getfirst(); // declaration of global friend 
}; 

class B 
{ 

public: 

    friend string :: getfirst(); // declaration of global friend 
    friend string A::getfirst(); // declaration of friend from other class 
}; 

.

+0

그것은 나를 위해 컴파일되지 않았다. 클래스 B에는 getfirst 멤버가 없다고한다. – user798774

관련 문제