单冒号“:”的重要性在C ++中 [英] Importance of a singlecolon ":" in C++

查看:113
本文介绍了单冒号“:”的重要性在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在常规代码中,我很少遇到
类中的单个冒号,例如:

Rarely in the regular codes I encounter the a single colon in classes for e.g.:

A::member():b(),c()
{
}

这里的单个冒号的重要性是什么?为什么在这里使用它?
有时是强制性的吗?

What is the importance of the single colon over here? Why is it used here? Is it mandatory sometimes? If so in which cases?

推荐答案

在这种情况下,使用单个冒号表示您正在使用初始化器列表初始化程序列表用于:

A single colon in this context is used to signal that you are using an initializer list. An initializer list is used to:


  • 从派生类调用基类构造函数

  • 初始化该类的成员变量

如其他人所述,初始化器列表可以仅在类构造函数上使用。

As noted by others, an initializer list can only be used on a class constructor.

虽然也可以在构造函数的主体中初始化成员变量,但出于以下几个原因通过初始化器列表

While it's also possible to initialize member variables in the body of the constructor, there are several reasons for doing so via the initializer list:


  • 常量指针引用不能从构造函数的主体中初始化

  • 通常使用 initializer列表更为有效,因为它将(从内存中)仅调用

  • Constant pointers or references cannot be initialized from the body of the constructor
  • It is usually more efficient to use the initializer list as it will (from memory) only invoke the constructor for the member, rather than the constructor and assignment operator which can be costly for non-POD types.

已经说了所有的内容,而不是非POD类型的成员的构造函数和成员赋值运算符。这样,您的代码格式有点奇怪。在我通常使用的代码中,使用初始化列表的缩进方式如下:

Having said all of this, the formatting of your code is a bit odd. In the code that I usually work with, use of an initializer list would be indented like this:

A::A()
    :b(),
     c()
{
}

这让我更清楚地知道 :: 用于在 A :: A()中定义类成员。

This makes it more clear to me that the : has no relation to the :: used to define class membership in A::A().

这篇关于单冒号“:”的重要性在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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