有人可以解释一下这个 C++句法?

发布于 2024-11-04 10:22:04 字数 672 浏览 1 评论 0原文

可能的重复:
构造函数中这个奇怪的冒号成员语法是什么?

你好,我最近在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

国粹 2024-11-11 10:22:04

初始化列表可用于初始化成员变量以及父变量。这是编写构造函数的正确方法 - 像这样的初始化比在构造函数主体中进行赋值更有效,并且在语义上可能更正确。

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.

淡淡離愁欲言轉身 2024-11-11 10:22:04

正如您所猜测的,这就是成员初始化的语法。 此对比:

class C
{
private:
  int i;
public:
  C(int i_) : i(i_) {} // initialization
};

class C
{
private:
  int i;
public:
  C(int i_) { i = i_; } // assignment
};

通常,初始化成员比在构造函数主体中分配给它们更好,并且在某些情况下这是必要的(一个例子是引用)。

That's the syntax for member initialization, as you surmised. Contrast this:

class C
{
private:
  int i;
public:
  C(int i_) : i(i_) {} // initialization
};

with:

class C
{
private:
  int i;
public:
  C(int i_) { i = i_; } // assignment
};

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文