【发布时间】:2016-12-07 19:47:04
【问题描述】:
想象一下我有
struct Foo
{
int a;
string s;
float f;
}
所以现在当我需要创建新的 Foo 时,我需要添加一个构造函数:
struct Foo
{
int a;
string s;
float f;
Foo(int a, string s, float f)
{
this->a = a;
this->s = s;
this->f = f;
}
}
然而,这种手动编写构造函数的方法非常耗时,尤其是对于具有 10 多个属性的结构/类。我的问题是:有没有办法自动生成这样的构造函数?
【问题讨论】:
-
IDE 代码自动生成? en.wikipedia.org/wiki/Builder_pattern ?程序代码生成? stackoverflow.com/questions/6273437/…(即聚合初始化)?反射库? ...我感觉到你在那里尝试做的事情有一种反模式,顺便说一句。
-
So now when I need to create new Foo I need to add a constructor不,你没有。不用一个,使用聚合初始化。 -
这称为“聚合初始化”。去谷歌,查一下。您将需要一个支持当前 C++ 标准的编译器。
-
@SamVarshavchik 好吧,
thing = {other, things}语法对于 C 兼容性始终有效,对吧?只有thing{uniform, initialisation}是 C++11 中的新选项。 -
另外,正如 Humam 所指出的,在初始化列表中分配可以初始化的内容是一个巨大的nope。有很多原因导致前者不适用于特定类型/资格的成员......即使它可以工作,它也是低效的(导致您的成员被默认初始化然后分配)和草率的风格。跨度>
标签: c++ class struct constructor code-generation