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

C++ 是否需要在头文件中定义初始化列表?,c++,initialization-list,C++,Initialization List,最近我创建了类Square: ==========头文件====== class Square { int m_row; int m_col; public: Square(int row, int col): m_row(row), m_col(col) }; #include "Square.h" Square::Square(int row, int col) { cout << "TEST"; } class Square {

最近我创建了类
Square

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

class Square
{
    int m_row;
    int m_col;

public:
    Square(int row, int col): m_row(row), m_col(col) 
};
#include "Square.h"

Square::Square(int row, int col)
{
    cout << "TEST";
}
class Square
{
    int m_row;
    int m_col;

public:
    Square(int row, int col): m_row(row), m_col(col) {};
};
=============cpp文件======

class Square
{
    int m_row;
    int m_col;

public:
    Square(int row, int col): m_row(row), m_col(col) 
};
#include "Square.h"

Square::Square(int row, int col)
{
    cout << "TEST";
}
class Square
{
    int m_row;
    int m_col;

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

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

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

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

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

class Square
{
    int m_row;
    int m_col;

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

class Square
{
    int m_row;
    int m_col;

public:
    Square(int row, int col);
};
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
其他地方。如果将其设置为
内联
初始化列表是构造函数定义的一部分,则允许在标题中使用“别处”,因此您需要在定义构造函数主体的同一位置定义它。
这意味着您可以将其保存在头文件中:

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

这种类型的初始化称为成员初始化列表的变量。成员初始化列表可以在头文件或源文件中使用。那没关系。但在头文件中初始化构造函数时,它必须具有定义。您可以参考以了解更多详细信息。

没有解释问题以及解决问题的原因。@下划线\u d初始化列表是定义的一部分,因此您必须将列表放置在使用定义/body/{}的位置。您应该从第一个代码示例中删除多余的分号。这似乎更好地回答了问题。