繁体   English   中英

C ++:在构造函数中调用成员函数?

[英]C++: calling member functions within constructor?

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

#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()吗?

看起来像是在end()之后插入;

在构造函数的主体中

IntList() { tail_ = begin(); }

构造基类并且可以调用它的成员,但是对于空列表,它应该返回end();

你的问题不是在构造函数中,而是在第一次调用append() 因为你的列表是空的,所以begin()等于end() end()是一个有效的迭代器,但之后的那个不是。 要解决该特定问题,请尝试调用insert()

在这就是说,一个快速偷看<ext/slist>确认的析构函数slist不是虚拟的,这意味着slist不旨在被源自。

slist <>的文档表明提供给insert_after的迭代器必须是可解除引用的。

由于您的列表为空,因此begin()返回end(),因此不能解除引用。

请参阅此处的文档

http://www.sgi.com/tech/stl/Slist.html

iterator insert_after(iterator pos,const value_type&x)

pos必须是* this中的可解除引用的迭代器。 (也就是说,pos可能不是end()。)在pos之后立即插入x的副本。 返回值是指向新元素的迭代器。 复杂性:恒定时间。

如果集合中没有元素,则.begin()无效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM