C++ 构造函数名称后面的冒号有什么作用?

What does a colon following a C++ constructor name do?(C++ 构造函数名称后面的冒号有什么作用?)

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

问题描述

冒号操作符(:")在这个构造函数中有什么作用?是否等价于MyClass(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.

构造函数的签名是:

MyClass();

这意味着可以不带参数调用构造函数.这使它成为默认构造函数,即,当您编写 MyClass someObject;.

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

: m_classID(-1), m_userdata(0) 部分称为初始化列表.这是一种使用您选择的值初始化对象的某些字段(如果需要,可以全部使用)的方法,而不是将它们保留为未定义.

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++ 构造函数名称后面的冒号有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++ 构造函数名称后面的冒号有什么作用?

基础教程推荐