是否需要在头文件中定义初始化列表

Is it required to define the initialization list in a header file?

本文关键字:定义 初始化 列表 文件 是否      更新时间:2023-10-16

最近我创建了类Square:

=============头文件======

class Square
{
    int m_row;
    int m_col;
public:
    Square(int row, int col): m_row(row), m_col(col) 
};

======cpp文件======

#include "Square.h"
Square::Square(int row, int col)
{
    cout << "TEST";
}

但后来我收到了很多错误。如果我删除cpp文件并将头文件更改为:

=============头文件======

class Square
{
    int m_row;
    int m_col;
public:
    Square(int row, int col): m_row(row), m_col(col) {};
};

它没有任何错误。这是否意味着初始化列表必须出现在头文件中?

初始化列表 是构造函数定义的一部分,因此您需要在定义构造函数主体的同一位置定义它。这意味着你可以在你的头文件中有它:

public:
    Square(int row, int col): m_row(row), m_col(col) {};

或在.cpp文件中:

Square::Square(int row, int col) : m_row(row), m_col(col) 
{
    // ...
}

但是当你在.cpp文件中有定义,然后在头文件中,应该只有它的声明:

public:
    Square(int row, int col);

您可以拥有

================头文件=============

class Square
{
    int m_row;
    int m_col;
public:
    Square(int row, int col);
};

===================cpp================

Square::Square(int row, int col):m_row(row), m_col(col) 
{}

初始化列表显示的是构造函数定义,而不是非定义的声明。所以,你的选择是:

Square(int row, int col): m_row(row), m_col(col) {}; // ctor definition

在类定义中或其他:

Square(int row, int col); // ctor declaration

在类定义和:

Square::Square(int row, int col): m_row(row), m_col(col) {} // ctor definition

其他地方。如果您将其设为inline,则允许在标头中使用"其他位置"。

不是要求。它也可以在源文件中实现。

// In a source file
Square::Square(int row, int col): m_row(row), 
                                  m_col(col) 
{}

这种初始化变量称为成员初始化列表。成员初始化列表可以用于头文件或源文件。那没关系。但当您在头文件中初始化构造函数时,它必须有定义。有关详细信息,请参阅C++成员初始化列表。