成员初始化
可能的重复:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
其他成员已经给出了理论上的答案。
实际上,在这些情况下使用成员初始化:
MyClass & mMyClass
)。您需要进行成员初始化,否则无法编译。const MyClass mMyClass
)。您还需要进行成员初始化,否则无法编译。MyClass mMyClass
,没有构造函数MyClass::MyClass()
)。您还需要进行成员初始化,否则无法编译。MyClass mMyClass
和sizeof(MyClass) = 1000000000
)。通过成员初始化,您只需构建一次。通过在构造函数中直接初始化,它被构建了两次。The theoretical answers have been given by other members.
Pragmatically, member-wise initialization is used in these cases :
MyClass & mMyClass
) in your class. You need to do a member-wise initialization, otherwise, it doesn't compile.const MyClass mMyClass
). You also need to do a member-wise initialization, otherwise, it doesn't compile.MyClass mMyClass
with no constructorMyClass::MyClass()
). You also need to do a member-wise initialization, otherwise, it doesn't compile.MyClass mMyClass
andsizeof(MyClass) = 1000000000
). With member-wise initialization, you build it only once. With direct initialization in the constructor, it is built twice.第一个使用初始化,第二个不使用初始化,它使用赋值。在第二个中,成员
x
和y
首先默认初始化(零),然后为它们分配a 和
b
。另请注意,在第二个中,仅当成员的类型具有非平凡默认构造函数时才对成员进行默认初始化。否则,就没有初始化(正如@James在评论中指出的那样)。
现在看这个主题就知道了:
First one uses initialization and second one does NOT use initialization, it uses assignment. In the second one, the members
x
andy
are default-initialized first (with zero), and then they're assigned witha
andb
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: