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

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

问题描述


可能重复:

C ++初始化列表


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

  class MyClass 
{
public:
MyClass ,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这么常见? >

解决方案

总之,如果可能的话,总是喜欢初始化列表。 2个原因:




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


  • 如mwigdahl和avada在其他答案中所提到的,const成员和引用成员只能在初始化列表中初始化。




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


Possible Duplicate:
C++ initialization lists

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;
}

Edit: Why is option 2 so common?

解决方案

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

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

  • 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天全站免登陆