C ++类引用 [英] C++ Class References

查看:126
本文介绍了C ++类引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自Delphi,我习惯使用类引用(元类)如下:

  type 
TClass = TForm类;
var
x:TClass;
f:TForm;
begin
x:= TForm;
f:= x.Create();
f.ShowModal();
f.Free;
end;

实际上,从TObject派生的每个X类都有一个名为ClassType的方法,返回一个可以使用的TClass创建X的实例。



在C ++中有什么类似的东西吗?

解决方案

很显然,现代的Delphi支持元类,与原来的Smalltalk非常相似。



在C ++中没有类似的东西。 p>

在C ++中模拟该特性的一个主要问题是,运行时动态分配表示类型的值,并能够从这些值创建实例,在C ++中需要静态地知道一个类型的构造函数以实例化。



可能你可以通过使用C ++实现很多相同的高级目标 static polymorphism ,其中包括函数重载和模板机制,而不是元类的极端运行时多态性



C ++的效果是使用可克隆的范例对象和/或几乎相同的想法多态对象工厂对象。前者是相当不寻常的,后者可以遇到现在和然后(主要是差异是参数化发生的地方:与examplar对象它的对象的状态,而对象工厂它的参数的创建函数)。个人而言,我会保持远离,因为C ++是为静态类型设计的,这个想法是关于C ++模拟一种具有非常不同的特性和编程风格的语言等。


Coming from Delphi, I'm used to using class references (metaclasses) like this:

type
  TClass = class of TForm;
var
  x: TClass;
  f: TForm;
begin
  x := TForm;
  f := x.Create();
  f.ShowModal();
  f.Free;
end;

Actually, every class X derived from TObject have a method called ClassType that returns a TClass that can be used to create instances of X.

Is there anything like that in C++?

解决方案

Apparently modern Delphi supports metaclasses in much the same way as original Smalltalk.

There is nothing like that in C++.

One main problem with emulating that feature in C++, having run-time dynamic assignment of values that represent type, and being able to create instances from such values, is that in C++ it's necessary to statically know the constructors of a type in order to instantiate.

Probably you can achieve much of the same high-level goal by using C++ static polymorphism, which includes function overloading and the template mechanism, instead of extreme runtime polymorphism with metaclasses.

However, one way to emulate the effect with C++, is to use cloneable exemplar-objects, and/or almost the same idea, polymorphic object factory objects. The former is quite unusual, the latter can be encountered now and then (mostly the difference is where the parameterization occurs: with the examplar-object it's that object's state, while with the object factory it's arguments to the creation function). Personally I would stay away from that, because C++ is designed for static typing, and this idea is about cajoling C++ into emulating a language with very different characteristics and programming style etc.

这篇关于C ++类引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆