C ++成员初始化列表 [英] C++ Member Initialization List

查看:133
本文介绍了C ++成员初始化列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请解释如何使用成员初始化列表。
我有一个在 .h 文件和 .cpp 文件中声明的类: p>

  class示例
{
private:
int m_top;
const int m_size;
...
public:
示例(int size,int grow_by = 1):m_size(5),m_top(-1);
...
〜Example();
};

我在对象创建时初始化 m_size 因为 const 。我该如何写构造函数?
我应该重复:m_size(5),m_top(-1),还是我可以省略这一步?

 示例::示例(int size,int grow_by)
{
...这里的一些代码
}

  :示例(int size,int grow_by):m_size(5),m_top(-1)
{
...这里的一些代码
}


解决方案

这是初始化列表:

 示例::示例(int size,int grow_by):m_size(5),m_top(-1)
{
...这里的一些代码
}

并且只能在cpp文件中进行。



当你这样做时,你不会得到一个错误,就像你在示例中的头一样。


Please explain how to use member initialization lists. I have a class declared in a .h file and a .cpp file like this:

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

I'm initializing m_size on object creation because of const. How should I write the constructor? Should I repeat : m_size(5), m_top(-1), or I can omit this step?

Example::Example( int size, int grow_by)
{
... some code here
}

or

Example::Example( int size, int grow_by) : m_size(5), m_top(-1)
{
... some code here
}

解决方案

This is the initialization list :

Example::Example( int size, int grow_by) : m_size(5), m_top(-1)
{
... some code here
}

and it should be done only in the cpp file.

Don't you get an error when you do it like you did in the header in your example?

这篇关于C ++成员初始化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆