2014-07-08 2 views
9

내 클래스의 보호 된 메서드 및 생성자를 테스트하려고합니다. 이를 위해, 나는 그것을 서브 클래스 및 C++ (11) using 키워드 public으로 회원을 다시 내보내려고 그러나'using'키워드를 사용하여 상속 된 생성자를 공개합니다.

class Foo { 
    protected: 
    Foo(int i) {} 
    void run() {} 
}; 

class TestableFoo : public Foo { 
    public: 
    using Foo::Foo; 
    using Foo::run; 
}; 

int main() { 
    TestableFoo foo(7); 
    foo.run(); 
} 

모두 g ++ 및 그 소리 ++ 다음과 같은 오류를 생성, 컴파일 실패 :

test.cpp:13:15: error: ‘TestableFoo::TestableFoo(int)’ is protected 
    using Foo::Foo; 
      ^
test.cpp:18:16: error: within this context 
    TestableFoo foo(7); 
        ^

run 메서드가 공용이더라도 테스트 가능한 Foo 생성자는 여전히 보호됩니다 (별도로 확인했습니다). 왜 이렇게이다? 두 가지 결정 (상속과 덮어 쓰기)을 이해할 수는 있지만 메서드와 생성자간에 불일치가있는 이유는 무엇입니까?

+0

관련 - http://stackoverflow.com/questions/24014240/c11-declaring-factory-a-friend-of-base-class을 - 왜 대답하지 않습니까? * 왜 * – Praetorian

+2

"이유"는 그렇지 않으면 아마도이 상황에서 상속받을 수 없다는 불편보다 악의적 인 것으로 간주 될 수있는 모든 생성자의 액세스 가능성을 변경하기 때문일 수 있습니다. 그러나 그것은 단지 추측입니다. –

답변

4

표준 명시 상속 생성자의 액세스 레벨을 유지한다고 :

12.9 상속 생성자 [class.inhctor]

1 A using-declaration (7.3.3) that names a constructor implicitly declares a set of inheriting constructors. The candidate set of inherited constructors from the class X named in the using-declaration consists of actual constructors and notional constructors that result from the transformation of defaulted parameters as follows:

[케이스에서 생략]

4 A constructor so declared has the same access as the corresponding constructor in X. It is deleted if the corresponding constructor in X is deleted (8.4).

을 물론 직접 호출 할 수도 있습니다.

TestableFoo(int i) : Foo(i) { } 
1

이 동작은 표준 (2011 12.9, §4 ISO/IEC에게 14,822 일) : 말씀을 준수입니다

X는 생성자가 상속되는 기본 클래스입니다

A constructor so declared has the same access as the corresponding constructor in X.

.

가 원하는 동작을 얻으려면, 당신은 사용할 수 있습니다

class TestableFoo : public Foo { 
    public : 
    TestableFoo(int i) : Foo(i) { } 
    using Foo::run; 
}; 
관련 문제