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.

我无法理解这是如何工作的,因为 allocate、dispose 和 operator 是纯虚拟的,所以它们各自的类实际上并没有定义这些函数。

4

2 回答 2

3

引用支持多态性。这意味着任何使用该函数的人printTranslatedArgs都需要使用基类调用它,TranslatorAllocator实现所有虚函数。你不需要关心函数内部的具体类类型,调用它们就好像它们是任何其他成员函数一样,例如:

char *p = a.allocate(5);
于 2012-12-14T07:45:22.267 回答
2

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

意味着可以使用任何实现 Translator/Allocator 中方法的类。

IOW 可以说抽象类定义了一个契约(接口),派生类必须实现这些方法才能完成契约。

例如 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);
  ...
}
于 2012-12-14T08:16:42.450 回答