简体   繁体   English

对象向量迭代器的分割错误

[英]Segmentation fault with iterator on object vector

Accessing class parameters and functions through the iterator fails, both when using -> and *. 使用->和*时,都无法通过迭代器访问类参数和函数。 Searched a lot of threads to no avail. 搜索了大量线程无济于事。 It wont let me submit the question unless more details are added so, hmm, co stands for connection and have been double checking const and pointer references all day. 除非添加更多详细信息,否则它不会让我提交问题,因此,hmm,co代表连接,并且整天都在仔细检查const和指针引用。

Snip: 片段:

vector<Axon>::iterator ait;
ait=axl.begin();
const Neuron* co=ait->get_conn();

Diet compilable code: 饮食可编译代码:

#include <iostream>
#include <vector>
using namespace std;

class Neuron;
class Axon;
class Neuron{
friend class Axon;
public:
    Neuron(int);
    void excite(double);
    void connect(const Neuron *);
    //void grow_ax();
private:
    double _exc;
    vector<Axon> axl;   
};
class Axon{
    friend class Neuron;
public:
    Axon();
    const Neuron* get_conn();
private:
    double cond; //conductivity
    const Neuron* connection;
};
Neuron::Neuron(int numax){
        _exc=0;
    vector<Axon> axl (numax,Axon());
}
Axon::Axon(){
    cond=1;
    connection=0;
}
void Neuron::connect(const Neuron * nP){
    vector<Axon>::iterator ait;
    ait=axl.begin();
    const Neuron* co=ait->get_conn(); //error is here,
    //if (ait->connection==0)           these don't work
            //ait->connection=nP;       <===
}
const Neuron* Axon::get_conn(){
    return connection;
}

int main(){
    Neuron n1=Neuron(1);
    Neuron n2=Neuron(0);
    Neuron* n2p=&n2;
    n1.connect(n2p);
}

Thanks in advance 提前致谢

ait=axl.begin();
const Neuron* co=ait->get_conn();

axl doesn't contain any elements, so, axl.begin() == axl.end() and you're dereferencing it. axl不包含任何元素,因此axl.begin() == axl.end()会取消引用它。 Derefencing std::vector::end() is an undefined behavior . 取消引用std::vector::end()未定义的行为

Look at your constructor: 看一下你的构造函数:

Neuron::Neuron(int numax){
    _exc=0;
    vector<Axon> axl (numax,Axon());
    // this is a declaration of local object
    // which will be destroyed at the end of the constructor
}

Note also, this: 另请注意,这是:

Neuron n1=Neuron(1);
Neuron n2=Neuron(0);

Should be 应该

Neuron n1(1);
Neuron n2(0);

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

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