我使用 C++ 已经有一段时间了,偶尔让我烦恼的一件事是我还没有弄清楚如何在 C++ 中完成这个 Delphi Factory 构造。
我无法弄清楚的关键部分是如何在 C++ 中传递对类类型的引用。在 Delphi 中,我们有“TClass”类型。这种类型的变量是对某个类的引用。我们可以使用class of MyClass
语法来限制类引用可以引用的类来定义新的类引用类型。
请注意,术语“Delphi 类引用”=/=“类的 C++ 实例”
对于那些不熟悉 Pascal 的人,变量是声明的,variable: type
而不是 C 风格的type variable
。同样,函数的返回类型出现在参数列表和名称之后。
我在下面的例子中压缩了语法以减少样板,因此向 Delphi 开发人员道歉,因为格式很糟糕。关键部分在评论中描述。
program demo;
{$APPTYPE CONSOLE}
// declarations
type
Base = class
public constructor Create(name: string); virtual;
end;
// Class reference which refers to Base and its descendants
BaseClass = class of Base;
ChildA = class(Base)
public constructor Create(name: string); override;
end;
ChildB = class(Base)
public constructor Create(name: string); override;
end;
// implementation
constructor Base.Create(name: string);
begin
WriteLn('Base says hi to ' + name);
end;
constructor ChildA.Create(name: string);
begin
inherited Create(name);
WriteLn('ChildA says hi to ' + name);
end;
constructor ChildB.Create(name: string);
begin
WriteLn('ChildB says hi to ' + name);
end;
// *** THIS IS THE BIT THAT I'M INTERESTED IN ***
// The function doesn't know at compile time exactly what class it is being
// asked to construct. The compiler knows that it is or inherits from Base.
// I can't find any kind of "class reference" in C++.
function ConstructSomething(ClassType: BaseClass; name: string): Base;
begin
Result := ClassType.Create(name);
end;
// Equivalent to "main()" in C
begin
// Pass references to a class to the ConstructSomething function
ConstructSomething(Base, 'Mark');
WriteLn('');
ConstructSomething(ChildA, 'Mark');
WriteLn('');
ConstructSomething(ChildB, 'Mark');
WriteLn('');
end.
输出:
Base says hi to Mark
Base says hi to Mark
ChildA says hi to Mark
ChildB says hi to Mark
请注意,当传递对子类的引用时,将创建子类。在此演示中,有意不调用 ChildB 中的基本构造函数,以使“类引用”概念更加明显。