【问题标题】:Is it required to define the initialization list in a header file?是否需要在头文件中定义初始化列表?
【发布时间】:2013-03-11 09:35:54
【问题描述】:

最近我创建了类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) {};
};

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

【问题讨论】:

    标签: c++ initialization-list


    【解决方案1】:

    初始化列表是构造函数定义的一部分,所以你需要在你定义构造函数体的地方定义它。 这意味着您可以在头文件中使用它:

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

    【讨论】:

    • 您应该从第一个代码示例中删除多余的分号。
    • 这似乎更好地回答了这个问题。
    【解决方案2】:

    你可以拥有

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

    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) 
    {}
    

    【讨论】:

    • 没有解释问题以及解决问题的原因。
    • @underscore_d 初始化列表是 definition 的一部分,因此您必须将列表放在使用定义/正文/ {} 的位置
    【解决方案3】:

    初始化列表与构造函数定义一起出现,而不是与不是定义的声明一起出现。因此,您的选择是:

    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,则允许在标题中包含“其他地方”。

    【讨论】:

      【解决方案4】:

      不是必需的。它也可以在源文件中实现。

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

      【讨论】:

        【解决方案5】:

        这种初始化变量称为成员初始化列表。成员初始化列表可以用在头文件或源文件中。那没关系。但是构造函数在头文件中初始化时必须有定义。您可以参考C++ Member Initialization List了解更多详情。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-10
          • 2015-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-19
          相关资源
          最近更新 更多