简体   繁体   English

构造函数是否必须在C ++中初始化成员变量?

[英]Do constructors have to initialize member variables in C++?

I have learned that constructors are used to initialize the member variables of a class in C++. 我了解到,构造函数用于初始化C ++中类的成员变量。 In all the examples I have seen the constructors initialize all the member variables of the class when called. 在所有示例中,我都看到构造函数在调用时初始化该类的所有成员变量。

What happens if I write a constructor that only initializes some or none of the member variables? 如果我编写仅初始化部分成员变量或不初始化任何成员变量的构造函数,会发生什么情况?

It really depends on what member variables you have. 这实际上取决于您拥有哪些成员变量。 If you provide a constructor and don't explicitly initialize a variable in the member initialization list, then it will be default initialized . 如果提供构造函数,并且未在成员初始化列表中显式初始化变量,则它将默认为initialized And this is for every variable. 这适用于每个变量。

Now, default initialization does something else depending on what variable you have. 现在,默认初始化根据您拥有的变量执行其他操作。 If you have a builtin type, like int or bool , then it will not be initialized to 0 or any other value, just like if you had: 如果您具有内置类型(如intbool ,则不会将其初始化为0或任何其他值,就像您有:

int value; // it has an indeterminate value

This also applies to arrays. 这也适用于数组。 If it is another class, then the default constructor of that class will be called, just like if you had: 如果是另一个类,则将调用该类的默认构造函数,就像您有以下情况一样:

struct Foo { /*something*/ };
Foo value; // calls default constructor, i.e. initializes object

it's fine.. you can also initialize your member variables in your member functions, then, just call the function in the constructor.. the important thing is to don't forget to initialize variables before using them.. 没关系。您还可以在成员函数中初始化成员变量,然后只需在构造函数中调用该函数即可。.重要的是在使用变量之前不要忘记初始化变量。

in short.. it's fine to not initialize your member variables in the constructor as long as you initialize them somewhere in the class before using them.. 简而言之..最好不要在构造函数中初始化成员变量,只要在使用它们之前在类中的某个地方初始化它们即可。

You are allowed to do that. 您可以这样做。 It isn't great practise though as you'll have a series of uninitialised member variables that could produce unexpected results 不过,这不是一个好习惯,因为您会有一系列未初始化的成员变量,这些变量可能产生意外结果

Depends on the class and your program. 取决于类和您的程序。 Does your class and program needs all of those variables in all of the cases. 您的班级和程序在所有情况下是否都需要所有这些变量。 if your class does require them then no errors or exception will occur otherwise your program might crash or something. 如果您的班级确实需要它们,则不会发生错误或异常,否则您的程序可能会崩溃或发生其他情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM