【发布时间】:2017-07-14 01:57:42
【问题描述】:
我在一些看起来很容易的事情上遇到了麻烦,所以我一定忽略了一些事情。
我需要构造一个类,该类的字段也是类(非 POD)。该字段的类有一个默认构造函数和一个“真实”构造函数。问题是我真的无法在初始化列表中构造字段,因为实际上构造函数有一个参数,它是一个需要有点复杂的 for 循环来填充的向量。
这是重现问题的最小示例。
ConstructorsTest.h:
class SomeProperty {
public:
SomeProperty(int param1); //Ordinary constructor.
SomeProperty(); //Default constructor.
int param1;
};
class ConstructorsTest {
ConstructorsTest();
SomeProperty the_property;
};
ConstructorsTest.cpp:
#include "ConstructorsTest.h"
ConstructorsTest::ConstructorsTest() {
the_property(4);
}
SomeProperty::SomeProperty(int param1) : param1(param1) {}
SomeProperty::SomeProperty() : param1(0) {} //Default constructor, doesn't matter.
但这会产生编译错误:
ConstructorsTest.cpp: In constructor 'ConstructorsTest::ConstructorsTest()':
ConstructorsTest.cpp:4:19: error: no match for call to '(SomeProperty) (int)'
the_property(4);
^
它并没有像通常那样提供有关本来可以使用哪些功能的建议。
在上面的例子中,我只是在初始化列表中初始化the_property,但实际上4实际上是一个需要先生成的复杂向量,所以我真的不能。将the_property(4) 移动到初始化列表会导致编译成功。
其他类似的线程提到对象必须有default constructor,或者it can't be const。这两个要求似乎都已满足。
【问题讨论】:
标签: c++ c++11 constructor initialization initializer-list