gpt4 book ai didi

c++ - 无法初始化初始化列表之外的字段

转载 作者:搜寻专家 更新时间:2023-10-31 02:10:32 26 4
gpt4 key购买 nike

我在处理看似非常简单的事情时遇到了麻烦,所以我一定是忽略了一些事情。

我需要构建一个类,该类的字段也是一个类(非 POD)。字段的类有一个默认构造函数和一个“真正的”构造函数。问题是我真的不能构造初始化列表中的字段,因为实际上构造函数有一个参数,它是一个 vector ,需要有点复杂的 for 循环来填充。

这是一个重现问题的最小示例。

构造函数测试.h:

class SomeProperty {
public:
SomeProperty(int param1); //Ordinary constructor.
SomeProperty(); //Default constructor.
int param1;
};

class ConstructorsTest {
ConstructorsTest();
SomeProperty the_property;
};

构造函数测试.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 实际上是一个需要先生成的复杂 vector ,所以我真的不能。将 the_property(4) 移动到初始化列表会导致编译成功。

其他类似的线程提到该对象必须有一个 default constructor ,或者那个it can't be const .在这里,这两个要求似乎都已得到满足。

最佳答案

您不能在构造函数体内初始化数据成员。 (the_property(4); 只是试图将 the_property 作为仿函数调用。)您只能像这样分配它们:

ConstructorsTest::ConstructorsTest() {
the_property = ...;
}

but in reality the 4 is actually a complex vector that needs to be generated first

您可以添加一个生成必要数据的成员函数,并使用它来初始化member initializer list 中的数据成员。 .例如

class ConstructorsTest {
...
static int generateData();
};

int ConstructorsTest::generateData() {
return ...;
}

ConstructorsTest::ConstructorsTest() : the_property(generateData()) {
}

关于c++ - 无法初始化初始化列表之外的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45093421/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com