Cas*_*sey 3 c++ struct initialization
这实际上是两个问题,如下所示:
目前,我有一些公共内部辅助结构(严格用于将数据作为一个对象传递),在构造类的实例期间,我尝试使用初始化列表而不是赋值,但编译器抱怨各个结构成员,因此我添加了结构的构造函数......但这似乎是我走上了错误的道路。
有没有一种方法可以在不使用构造函数的情况下初始化初始化列表中的结构?
这些助手是否更适合作为外部类?
class Foo {
public:
//...
struct Bar {
double mass;
std::pair<double, double> gravMod;
std::pair<double, double> position;
std::pair<double, double> velocity;
bool falling;
Bar() : mass(0.0), gravMod(std::make_pair(0.0, 0.0)), position(std::make_pair(0.0, 0.0)), velocity(std::make_pair(0.0, 0.0)), falling(false) { };
Bar(double _mass, std::pair<double, double> _gravMod, std::pair<double, double> _position, std::pair<double, double> _velocity, bool _falling)
: mass(_mass), gravMod(_gravMod), position(_position), velocity(_velocity), falling(_falling) { }
Bar(const Bar& other)
: mass(other.mass), gravMod(other.gravMod), position(other.position), velocity(other.velocity), falling(other.falling) { }
};
struct Baz {
std::pair<double, double> acceleration;
std::pair<double, double> force;
Baz() : acceleration(std::make_pair(0.0, 0.0)), force(std::make_pair(0.0, 0.0)) { }
Baz(std::pair<double, double> _acceleration, std::pair<double, double> _force)
: acceleration(_acceleration), force(_force) { }
Baz(const Baz& other) : acceleration(other.acceleration), force(other.force) { }
};
//...
protected:
//...
private:
Bar _currBar;
Bar _prevBar;
Baz _currBaz;
Baz _prevBaz;
};
编辑
示例及其相关错误:
Foo::Foo() : _currBar{0.0, std::make_pair(0.0, 0.0), std::make_pair(0.0, 0.0), std::make_pair(0.0, 0.0), false}, _currBaz{std::make_pair(0.0, 0.0), std::make_pair(0.0, 0.0)} { }
_currBar{抛出:expected '('. 第一个}抛出:expected';'。
Foo::Foo() : _currBar.mass(0.0), _currBar.gravMod(std::make_pair(0.0, 0.0)), _currBar.position(std::make_pair(0.0, 0.0)), _currBar.velocity(std::make_pair(0.0, 0.0)), _currBar.falling(false) { }
第一个_currBar.抛出:expected '('。之后全部_currBar.扔掉Member 'Foo::_currBar' has already been initialized.。
在 C++03 中,无法初始化嵌套的各个字段struct,也无法初始化嵌套数组的各个字段。在 C++0x(我猜现在是 C++11)中,他们放宽了这个限制,您可以struct使用如下语法初始化嵌套:
Foo::Foo() : _currBar{fieldOneValue, fieldTwoValue, /* ... */, fieldNValue}, /* ... etc ... */
Run Code Online (Sandbox Code Playgroud)
struct在我们等待更多编译器完全支持此功能的过程中,将构造函数添加到嵌套中是一个完全可行的选择。