鉴于
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都是纯虚拟的,因此它们各自的类实际上并没有定义这些函数。
答案 0 :(得分:3)
引用支持多态性。这意味着使用函数printTranslatedArgs
的任何人都需要使用实现所有虚函数的Translator
和Allocator
基类来调用它。你不需要为函数内部的具体类类型打扰,就像它们是任何其他成员函数一样调用它们,例如:
char *p = a.allocate(5);
答案 1 :(得分:2)
void printTranslatedArgs(int argc, char *argv[],
Translator &t, Allocator &a);
表示可以使用在Translator / Allocator中实现方法的任何类。
我可以说抽象类定义了一个契约(接口),派生类必须实现这些方法才能完成契约。
e.g。 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);
...
}