C++:在构造函数中初始化变量的位置 [英] C++: Where to initialize variables in constructor

查看:26
本文介绍了C++:在构造函数中初始化变量的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在选项 1 和选项 2 中初始化变量的优缺点是什么?

What are the pros/cons of initializing variables at option 1 vs option 2?

class MyClass
{
public:
    MyClass( float f, char a );
private:
    float mFloat;
    char mCharacter;
    bool mBoolean;
    int mInteger;
};

MyClass::MyClass( float f, char a ) : mFloat( f ), mBoolean( true ) // option 1.
{
    // option 2
    mCharacter = a;
    mInteger = 0;
}

为什么选项 2 如此普遍?

Why is option 2 so common?

推荐答案

简而言之,只要可能,总是首选初始化列表.2个原因:

In short, always prefer initialization lists when possible. 2 reasons:

  • 如果你没有在类的初始化列表中提到一个变量,构造函数将在进入你编写的构造函数的主体之前默认初始化它.这意味着选项 2 将导致每个变量被写入两次,一次用于默认初始化,一次用于构造函数体中的赋值.

  • If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, once for the default initialization and once for the assignment in the constructor body.

此外,正如 mwigdahl 和 avada 在其他答案中提到的,const 成员和引用成员可以在初始化列表中进行初始化.

Also, as mentioned by mwigdahl and avada in other answers, const members and reference members can only be initialized in an initialization list.

还要注意,变量总是按照它们在类声明中声明的顺序进行初始化,而不是按照它们在初始化列表中列出的顺序进行初始化(如果启用了适当的警告,编译器会在列表写错时发出警告)).同样,在类的析构函数中的代码执行完毕后,析构函数将以相反的顺序调用成员析构函数,在类声明中从最后到第一个.

Also note that variables are always initialized on the order they are declared in the class declaration, not in the order they are listed in an initialization list (with proper warnings enabled a compiler will warn you if a list is written out of order). Similarly, destructors will call member destructors in the opposite order, last to first in the class declaration, after the code in your class's destructor has executed.

这篇关于C++:在构造函数中初始化变量的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆