C ++:在构造函数中调用成员函数? [英] C++: calling member functions within constructor?

查看:244
本文介绍了C ++:在构造函数中调用成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码引发了运行时错误:

The following code raises a runtime error:

#include <iostream>
#include <iterator>
#include <ext/slist>

class IntList :  public __gnu_cxx::slist<int> {
public:
    IntList() { tail_ = begin(); } // seems that there is a problem here
    void append(const int node) { tail_ = insert_after(tail_, node); }

private:
    iterator tail_;
};

int main() {
    IntList list;

    list.append(1);
    list.append(2);
    list.append(3);

    for (IntList::iterator i = list.begin(); i != list.end(); ++i) {
        std::cout << *i << " ";
    }

    return 0;
}

看起来问题在于构造函数 IntList )。是因为它调用成员函数 begin()

Seems that the problem is in the constructor IntList(). Is it because it calls the member function begin()?

推荐答案

看起来你在end()之后插入

Looks like You are inserting after end();

在构造函数的正文中

IntList() { tail_ = begin(); }

基类被构造并且它的成员可以被调用,但是对于一个空列表, return end();

the base class is constructed and it's members can be called, but for an empty list, it should return end();

这篇关于C ++:在构造函数中调用成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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