close

原文:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Interface

C++並沒有定義interface這個關鍵字(Java和C#有定義interface關鍵字),在C++中只要有class或struct(class和struct的功能幾乎相同)符合下列條件,我們就可以稱之為interface:
* 所有的method都為pure virtual method或static method
* 不能有任何的non-static data members
* 沒有定義任何ctor;如果有定義ctor的話,該ctor必須設為protected,並且不能有任何的parameter
* 如果它有繼承其他的classes,這些classes也都必須符合interface的條件

Google C++ Style Guide建議符合以上條件的class或struct,要採用以Interface作為後綴的naming rule,雖然這樣的後綴有點冗長(mircosoft的interface naming rule是以I作為前綴),但這樣的規定確保未來maintain程式碼時,一眼就可以看出哪些class或struct是interface。其實Google C++ Style Guide沒有強制規定一定要使用Interface後綴,但是如果你用了Interface作為class或struct的後綴,那該class或struct就必須符合上述的那些條件。

Interface classes不能直接instantiate,因為它們有pure virtual functions;通常會使用interface class是因為不希望client端知道時作的細節,所以這些interface classes的實作將會放在它們的subclass中,也因如此interface classes必須宣告virtual dtor確保subclass中的dtor會被呼叫,而沒有memory leak的風險。

arrow
arrow
    文章標籤
    C++
    全站熱搜

    coherence 發表在 痞客邦 留言(0) 人氣()