2012-12-14 32 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); 
    ... 
}