2012-12-14 34 views
4

鑑於使用抽象概念進行翻譯

class Allocator { 
    public: 
    virtual char *allocate(unsigned int size)=0; 
     // EFF: allocates a character buffer of size characters 
    virtual void dispose(char *buf)=0; 
     // REQ: buf was allocated by this allocator 
     // EFF: release memory previously allocated. 
}; 
class Translator { 
    public: 
    virtual char *operator()(const char *s, Allocator &a) = 0; 
     // EFF: returns a translation of the C-string s as 
     //  another C-string, where the translation 
     //  C-string is allocated by a. 
}; 

假設你想實現以下:

void printTranslatedArgs(int argc, char *argv[], 
         Translator &t, Allocator &a); 
    // REQ: argc/argv are in the form of program arguments 
    // EFF: prints the translated command line. 

我無法理解這是如何工作,因爲分配,部署,和運營商都是純虛擬的,所以他們是各自的類實際上並沒有定義這些功能。

回答

3

參考支持多態。這意味着,不管是誰使用功能printTranslatedArgs必須與實現所有的虛函數的TranslatorAllocator基類來調用它。你不需要操心函數內部的具體類型,打電話給他們,如果他們是任何其他成員的功能,如:

char *p = a.allocate(5); 
+0

實際上,我怎麼叫他們在這裏有關係嗎? – user1903336

+0

因爲如果他們有函數定義你會使用它。 'char * p = a.allocate(5)'等 –

2

void printTranslatedArgs(int argc, char *argv[], 
         Translator &t, Allocator &a); 

意味着實現任何類可以使用Translator/Allocator中的方法。

IOW一個可以說,抽象類定義了合同(接口)和派生類必須以fullfill合同實現這些方法。

例如MyTranslator實現了虛擬方法char* operator()

class MyTranslator : public Translator 
{ 
public: 
virtual char *operator()(const char *s, Allocator &a) { /*...*/ } 
}; 

// omitted decl/def of MyAllocator 

int main(int argc,char* argv[]) 
{ 
    MyTranslator foo; 
    MyAllocator bar; 
    printTranslatedArgs(argc,argv,foo,bar); 
    ... 
}