有人可以解释一下这个 C++句法?
可能的重复:
构造函数中这个奇怪的冒号成员语法是什么?
你好,我最近在 C++ 程序中遇到了这种语法。这不是将参数传递给基类构造函数,因为我知道它是什么样子以及如何对其进行编码。这看起来像是类的某种变量初始化......这是代码:
class Particle
{
private:
bool movable;
float mass;
Vec3 pos;
Vec3 old_pos;
Vec3 acceleration;
Vec3 accumulated_normal;
public:
Particle(Vec3 pos)
: pos(pos),
old_pos(pos),
acceleration(Vec3(0,0,0)),
mass(1),
movable(true),
accumulated_normal(Vec3(0,0,0))
{}
Particle() {}
// More unrelated code
};
Possible Duplicate:
What is this weird colon-member syntax in the constructor?
Hi, I recently came across this syntax in a C++ program. This is not passing parameters to a base class constructor as I know what that looks like and how to code it. This looks like some sort of variable initialization for the class... Here is the code:
class Particle
{
private:
bool movable;
float mass;
Vec3 pos;
Vec3 old_pos;
Vec3 acceleration;
Vec3 accumulated_normal;
public:
Particle(Vec3 pos)
: pos(pos),
old_pos(pos),
acceleration(Vec3(0,0,0)),
mass(1),
movable(true),
accumulated_normal(Vec3(0,0,0))
{}
Particle() {}
// More unrelated code
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
初始化列表可用于初始化成员变量以及父变量。这是编写构造函数的正确方法 - 像这样的初始化比在构造函数主体中进行赋值更有效,并且在语义上可能更正确。
Initialisation lists can be used to initialise member variables as well as parents. This is the correct way of writing a constructor - initialisation like this is more efficient than doing assignment in the constructor body, and is likely semantically more correct.
正如您所猜测的,这就是成员初始化的语法。 此对比:
与
通常,初始化成员比在构造函数主体中分配给它们更好,并且在某些情况下这是必要的(一个例子是引用)。
That's the syntax for member initialization, as you surmised. Contrast this:
with:
It's generally better to initialize members rather than assigning to them in the constructor body, and there are some cases where it's essential (one example would be references).