请解释如何使用成员初始化列表。
我有一个在.h
文件和.cpp
文件中声明的类,如下所示:
class Example
{
private:
int m_top;
const int m_size;
...
public:
Example ( int size, int grow_by = 1 ) : m_size(5), m_top(-1);
...
~Example();
};
由于m_size
,我正在初始化const
对象创建。我该如何编写构造函数?
我应该重复: m_size(5), m_top(-1)
,还是可以省略这一步?
Example::Example( int size, int grow_by)
{
... some code here
}
或
Example::Example( int size, int grow_by) : m_size(5), m_top(-1)
{
... some code here
}
答案 0 :(得分:58)
只是澄清一些其他答案中出现的内容......
不要求初始化列表在源(.cpp)或头文件(.h)中。实际上,编译器不区分这两种类型的文件。重要的区别在于构造函数declaration和它的定义。初始化列表与定义一致,而不是声明 通常,声明在头文件中,定义在源文件中,但是,这不是语言的要求(即它将编译)。 当构造函数为空或短时,在类声明中内联提供构造函数定义并不罕见。在这种情况下,初始化列表将进入类声明,该声明可能位于头文件中。
<强> MyClass.h 强>
class MyClass
{
public:
MyClass(int value) : m_value(value)
{}
private:
int m_value;
};
答案 1 :(得分:22)
这是初始化列表:
Example::Example( int size, int grow_by) : m_size(5), m_top(-1)
{
... some code here
}
,它应该只在cpp文件中完成。
执行此操作时,如果您在示例中的标题中出现错误,是否会出现错误?
答案 2 :(得分:13)
成员初始化列表是源文件中定义的一部分 在cpp文件中写下:
Example ( int size, int grow_by) : m_size(5), m_top(-1)
{
}
头文件应该只有:
Example ( int size, int grow_by = 1 );
头文件只声明构造函数,Member Initializer列表不是声明的一部分。
答案 3 :(得分:9)
添加其他答案,关于初始化列表应该记住的最重要的事情是, the order of initialization is decided in the order in which the data members are declared, not the the order in which you have initialized the data members using initialization list
考虑一下这个例子(你的):
class Example
{
private:
int m_top;
const int m_size;
...
public:
Example ( int size, int grow_by = 1 ) : m_size(5), m_top(-1){}
/* Though size is initialized with a value first
But it is m_top variable that is assigned value -1
before m_size is assigned value 5 */
...
~Example(){}
};
如果一个人不知道上述情况,可能会造成非常严重的影响。
答案 4 :(得分:1)
在C ++ 11中,您可以使用non-static data member initialization。如果您有多个构造函数需要成员变量的公共值,这将特别有用。
class Example
{
private:
int m_top = -1;
const int m_size = 5;
...
public:
Example ( int size, int grow_by = 1 );
...
~Example();
};
...
Example::Example( int size, int grow_by )
{
... some code here
}
如果需要,可以覆盖构造函数中的值。
答案 5 :(得分:1)
您不能在标头和cpp中都有初始化列表。列表应该在哪个文件中定义构造函数。此外,您必须为构造函数包含一个实体,即使它是空的。
另外,您应该只在函数原型中指定默认参数,而不是在定义中。