成员初始化

发布于 2024-11-19 18:34:49 字数 384 浏览 5 评论 0原文

可能的重复:
C++ 初始化列表

类中的成员初始化和直接初始化之间有什么区别? 类中定义的两个构造函数有什么区别?

class A
{
    public:
    int x;
    int y;
    A(int a, int b) : x(a), y(b)
    {}

    A(int a, int b)
    {
        x = a;
        y = b;
    }
};

Possible Duplicate:
C++ initialization lists

What is the difference between member-wise initialization and direct initialization in a class?
What is the difference between the two constructors defined in the class?

class A
{
    public:
    int x;
    int y;
    A(int a, int b) : x(a), y(b)
    {}

    A(int a, int b)
    {
        x = a;
        y = b;
    }
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

剩一世无双 2024-11-26 18:34:49

其他成员已经给出了理论上的答案。

实际上,在这些情况下使用成员初始化:

  • 您的类中有一个引用属性 (MyClass & mMyClass)。您需要进行成员初始化,否则无法编译。
  • 您的类中有一个常量属性 (const MyClass mMyClass)。您还需要进行成员初始化,否则无法编译。
  • 您的类中有一个没有默认构造函数的属性MyClass mMyClass,没有构造函数MyClass::MyClass())。您还需要进行成员初始化,否则无法编译。
  • 您有一个异常大的属性对象(MyClass mMyClasssizeof(MyClass) = 1000000000)。通过成员初始化,您只需构建一次。通过在构造函数中直接初始化,它被构建了两次。

The theoretical answers have been given by other members.

Pragmatically, member-wise initialization is used in these cases :

  • You have a reference attribute (MyClass & mMyClass) in your class. You need to do a member-wise initialization, otherwise, it doesn't compile.
  • You have a constant attribute in you class (const MyClass mMyClass). You also need to do a member-wise initialization, otherwise, it doesn't compile.
  • You have an attribute with no default constructor in your class (MyClass mMyClass with no constructor MyClass::MyClass()). You also need to do a member-wise initialization, otherwise, it doesn't compile.
  • You have a monstruously large attribute object (MyClass mMyClass and sizeof(MyClass) = 1000000000). With member-wise initialization, you build it only once. With direct initialization in the constructor, it is built twice.
世界和平 2024-11-26 18:34:49

第一个使用初始化,第二个不使用初始化,它使用赋值。在第二个中,成员 xy 首先默认初始化(),然后为它们分配a 和 b

另请注意,在第二个中,仅当成员的类型具有非平凡默认构造函数时才对成员进行默认初始化。否则,就没有初始化(正如@James在评论中指出的那样)。

现在看这个主题就知道了:

First one uses initialization and second one does NOT use initialization, it uses assignment. In the second one, the members x and y are default-initialized first (with zero), and then they're assigned with a and b respectively.

Also note that in the second one, members are default initialized only if the types of members are having non-trivial default constructor. Otherwise, there is no initialization (as @James noted in the comment).

Now see this topic to know:

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