初始化const指针 - c ++中的初始化列表

Kub*_*tny 0 c++

我目前正在尝试用C++实现树结构.我开始使用以下代码:

class Tree {
    Node * const first;
    Node * last;
public:

    Tree(Node * const root)             
        {
            first = root;
            last = first;
        };
}
Run Code Online (Sandbox Code Playgroud)

但当然它给了我这些错误:

错误:未初始化的成员'Tree :: first'与'const'类型'Node*const'[-fpermissive]

错误:只读成员'Tree :: first'的分配

我调查了问题,发现我必须使用initializer list.我试过了,但是进展不顺利.

Tree(Node * const root)
:first()              
{
    first->id = 0;
    first->sibling = first;
    first->point = root->point;
    last = first;
};
Run Code Online (Sandbox Code Playgroud)

有了这个,问题以"运行失败"结束,没有错误,没有例外.

所以我甚至尝试过:

Tree(Node * const root)
:first()              
{
};
Run Code Online (Sandbox Code Playgroud)

但是甚至没有调用Node构造函数..

那么我做错了什么?

jua*_*nza 6

您还没有初始化你的const指针,但分配给它.事实上const,你不能这样做.您必须在构造函数初始化列表中初始化它:

Tree(Node * const root) : first(root)
{
  ....
}
Run Code Online (Sandbox Code Playgroud)

请记住,一旦到达构造函数的主体,所有数据成员都已初始化,无论是隐式还是显式.