【发布时间】:2011-07-21 20:28:57
【问题描述】:
这确实是两个问题,如下所示:
目前我有一些公共的内部辅助结构(严格用于将数据作为一个对象传递),在构造类的实例期间,我尝试使用初始化列表而不是赋值,但编译器抱怨个别结构成员所以我在结构中添加了构造函数……但这似乎是我走错了路。
有没有办法在不使用构造函数的情况下在初始化列表中初始化结构?
这些助手会更适合作为外部类吗?
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++ struct initialization