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.

割り当て、破棄、および演算子は純粋な仮想であり、それぞれのクラスは実際にはこれらの関数を定義していないため、これがどのように機能するかを理解するのに苦労しています。

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 に答える