最近我创建了类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);
关于c++ - 是否需要在头文件中定义初始化列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15335193/