是否需要在头文件中定义初始化列表
Is it required to define the initialization list in a header file?
最近我创建了类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++成员初始化列表。
相关文章:
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- Boost Python Numpy - 要初始化的未定义引用
- 虚拟成员函数的定义是否强制在同一转换单元中动态初始化静态数据成员?
- C++类中的类作为自定义向量(如何初始化?
- 初始化类定义中的结构数组
- C++ 如何检查 char 变量是否未定义(未初始化)
- C++列表初始化允许多个用户定义的转换
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- (C++)我的自定义数组无法初始化(编译错误)
- 类模板静态数据成员定义/声明/初始化
- 初始化在类类型 #define 中定义的非静态成员数组,不带默认 ctor
- 在另一个文件中初始化的 extern 数组中未定义的引用
- thread_local静态成员模板定义:初始化失败,GCC
- 通过用户定义的转换初始化引用
- 自定义初始化数组与 std::make_unique
- C++具有自定义初始化的静态调度
- 导入错误:动态模块未定义初始化函数
- 有没有一种标准的方法可以在初始化阶段运行一些代码并定义初始化的顺序
- C++,为什么我不能把带有参数的类构造函数的定义-初始化列表放在类声明之外
- 是否需要在头文件中定义初始化列表