繼承

2008-09-30 50 views
3

假設我有以下聲明:繼承

class Over1 
{ 
    protected: 
     class Under1 
     { 
     }; 
}; 

我知道我可以做到以下幾點:

class Over2 : public Over1 
{ 
    protected: 
     class Under2 : public Under1 
     { 
     }; 
}; 

但有申報Under2沒有Over2的方法嗎?

由於您必須將Over1擴展到使用Under1的任何派生項,這可能看起來很愚蠢,但在這種情況下可能會有30種不同的Under的風味。我可以:

  • 把他們所有的內部Over1:不 吸引力,因爲Over2只能使用 1或2其中
  • 把它們各自在 自己過的版本:不 吸引力的,因爲那麼你將有 繼承幾乎相同的類繼承 。
  • 找到一種方法,而無需創建 兒童Over1

因此,這是可能創造1退休的 孩子?

謝謝。

回答

1

使用模板和明確的特化可以在Over1中只使用一個額外的類聲明來完成此操作。

class Over1 
{ 
protected: 
    class Under1 
    { 
    }; 

    template <typename T> 
    class UnderImplementor; 
}; 

struct Under2Tag; 
struct Under3Tag; 
struct Under4Tag; 

template <> 
class Over1::UnderImplementor<Under2Tag> : public Over1::Under1 
{ 
}; 

template <> 
class Over1::UnderImplementor<Under3Tag> : public Over1::Under1 
{ 
}; 

template <> 
class Over1::UnderImplementor<Under4Tag> : public Over1::Under1 
{ 
}; 

希望這會有所幫助。

1

比創建嵌套類更好,您可能想要將這些關閉嵌入到名稱空間中。這樣,你不需要外部類來獲得內部類。在Google C++ Style Guide中有一些很好的論點。

0

如果你想保持Under1保護,那麼根據定義,你需要從Over1繼承來訪問它。我會建議讓Under1公開,或者像道格拉斯建議的那樣使用命名空間。

我沒有編譯器現在來測試這些了,所以我不能肯定這些工作,但你可以試試這個:

class Over1 
{ 
    protected: 
     class Under1 
     { 
     }; 

    public: 
     class Under1Interface : public Under1 
     { 
     }; 
}; 

class Under2 : public Over1::Under1Interface 
{ 
}; 

或許是這樣的:

class Over1 
{ 
    protected: 
     class Under1 
     { 
     }; 
}; 

class Under2 : private Over1, public Over1::Under1 
{ 
}; 

甚至:

class Under2; 

class Over1 
{ 
    friend class Under2; 

    protected: 
     class Under1 
     { 
     }; 
}; 

class Under2 : public Over1::Under1 
{ 
}; 

雖然那樣會暴露所有Over1s士兵到Under2的 - 不太可能是你想要的東西。

0

聽起來有點像我這個時髦的設計。爲什麼不嘗試以不同的方式構建代碼。我認爲這可能是裝飾者模式的一個很好的候選者,你可以在各種裝飾器中包裝你的基類來實現所需的功能,「下」的各種風格可能是裝飾器。只是一個想法,很難說不知道更多關於你的代碼的意圖。