C++ 初始化列表

标签 c++ list class initialization

下面是我不完全理解的初始化列表的代码。特别是它是页面中的最后一 block (red(Bow("red")) 和 blue(Bow("blue"))。

Bow 是包含在 .h 文件中的另一个类,其构造函数的形式为 Bow(string aColor)

初始化语法为

ClassName(argumentlist): datamember1(value1), dataMember2(value2){}

我不明白这个初始化是如何工作的。我理解在类 ArcheryCompetition 中创建类 Bow 的对象,这几乎就像在另一个构造函数的初始化列表中调用另一个类的构造函数一样。这些都是我正在阅读的初学者书籍。

如果需要更多说明,请告诉我。

class ArcheryCompetition
{
//member variables

private:
    //variables
    int rounds;
    float redScore;
    Bow red;

    float blueScore;
    Bow blue;

public:
    //constructor
    ArcheryCompetition( int lrounds);
    //destructor
    ~ArcheryCompetition();

    //methods
    int compete(void);

};

ArcheryCompetition::ArcheryCompetition(int lrounds):
rounds(lrounds), red(Bow("red")), blue(Bow("blue")), redScore(0), blueScore(0)**
{
}

最佳答案

由于成员 redblue 都是 Bow 类的实例,调用 red("red")blue("blue")。它将使用选定的参数调用类 Bow 的构造函数:

ArcheryCompetition::ArcheryCompetition(int lrounds):
rounds(lrounds), red("red"), blue("blue"), redScore(0), blueScore(0)
{
}

red(Bow("red")) 实际上是调用Bow 类的复制构造函数 .

Bow(const Bow& toCopy); 

它创建 Bow 的临时实例,使用“red”参数调用其构造函数,并将该临时对象逐字节复制到为 red 成员保留的内存中。我知道这可能有点令人困惑,而且我不知道为什么将此类构造放在书中而没有解释什么是复制构造函数。

在这里你可以找到一些很好的解释: http://www.cplusplus.com/articles/y8hv0pDG/

关于C++ 初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17161129/

相关文章:

list - Lisp - 检查符号是否在列表列表中

c++ - 为什么不为左值和右值重载 operator[]?

c++ - 如何组合两个查询并将第一个查询的结果用作第二个查询的输出

python - 返回第三列处具有最大值的子列表的第一项

c++ - 对象在另一个对象的变量内消失

java - Android - 如何声明 'this' 的变量?

ios - CLLocationManager - 授权提示消失了吗?

c++ - 强制 Qt5 从 exe 目录加载 SSL dll

C++/CX - GetFileAsync 抛出断点错误

java - 链表排序问题