C ++构造函数名后的冒号是什么? [英] What does a colon following a C++ constructor name do?

查看:120
本文介绍了C ++构造函数名后的冒号是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

冒号运算符(:)在此构造函数中执行什么操作?它等效于 MyClass(m_classID = -1,m_userdata = 0);

  class MyClass {
public:

MyClass():m_classID(-1),m_userdata(0){
}

m_classID;
void * m_userdata;
};


解决方案

这是初始化列表

 <$> 

c $ c> MyClass();

这意味着可以使用无参数调用构造函数。这使得它成为默认构造函数,即在你写 MyClass someObject; 时默认调用的构造函数。



部分:m_classID(-1),m_userdata(0)称为初始化列表。它是一种方法来初始化你的对象的一些字段(如果你愿意的话),使用你选择的值,而不是将它们保留为未定义。



初始化列表,构造函数体(在你的例子中恰好是空的)被执行。在里面你可以做更多的赋值,但一旦你输入了所有的字段已经被初始化 - 无论是随机,未指定的值,还是在初始化列表中选择的值。这意味着您在构造函数主体中执行的分配不会是初始化,而是值的更改。


What does the colon operator (":") do in this constructor? Is it equivalent to MyClass(m_classID = -1, m_userdata = 0);?

class MyClass {
public:

    MyClass() : m_classID(-1), m_userdata(0) { 
    }

    int m_classID;
    void *m_userdata;
};

解决方案

This is an initialization list, and is part of the constructor's implementation.

The constructor's signature is:

MyClass();

This means that the constructor can be called with no parameters. This makes it a default constructor, i.e., one which will be called by default when you write MyClass someObject;.

The part : m_classID(-1), m_userdata(0) is called initialization list. It is a way to initialize some fields of your object (all of them, if you want) with values of your choice, instead of leaving them as undefined.

After executing the initialization list, the constructor body (which happens to be empty in your example) is executed. Inside it you could do more assignments, but once you have entered it all the fields have already been initialized - either to random, unspecified values, or to the ones you chose in your initialization list. This means the assignments you do in the constructor body will not be initializations, but changes of values.

这篇关于C ++构造函数名后的冒号是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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