: Base(int x): x{x}{}是什么意思?

  • 本文关键字:是什么 Base int c++
  • 更新时间 :
  • 英文 :


我正在网上浏览一些教程,发现一个c++代码片段,我无法弄清楚这个代码片段到底是做什么的。我需要这样的信息,这个概念被称为什么,为什么它被使用。

代码是:

class Base{
int x;
public:
Base(){}
Base(int x): x{x}{} // this line i am unable to understand.
};

我想知道这5日线是什么,什么是发生在编译时编译器。

是这样的:

Base(int x) : 
// initialization of members
x{ x }  // aggregate initialization of member x with parameter x
// https://en.cppreference.com/w/cpp/language/aggregate_initialization
{
// empty function
}

让我们从下面开始:

  1. 定义中对应构造函数后面的:表示"成员初始化"。

  2. x是一个整数

  3. c++可以使用大括号初始化原始数据类型。参见:https://www.educative.io/edpresso/declaring-a-variable-with-braces-in-cpp

  4. 因此,x{x}将x初始化为构造函数的传入值。

  5. 最后一个{}是用来调用构造函数本身的。

最新更新