访问矢量类成员时的分段错误

时间:2017-03-17 17:34:25

标签: c++ class vector segmentation-fault member

我在c ++的这一行有一个分段错误:

vector<TemplateElement*> children = getChildren();

That继承自抽象类TemplateElement 如何解决?

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
#include "strings.h"
#include "aimlthat.h"

using namespace std;
using namespace aiml;

vector<string> That::elements() {
    vector<TemplateElement*> children = getChildren();
    vector<string> elements;

    for (int i = 0, n = children.size(); i < n; i++) {
        string text = children[i]->toString();
        text = trim(text);
        vector<string> vsText = split(text);

        for(int j=0, m=vsText.size(); j<m; ++j) {
            elements.push_back(vsText[j]);
        } 
    }

    return elements;
}

/ ********************************************** ********* /

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <map>
#include "strings.h"
#include "aimltemplateelement.h"
#include "aimltext.h"

using namespace std;
using namespace aiml;

vector<TemplateElement*> TemplateElement::getChildren() {
    return m_vtChildren;
}

/ ********************************************** ******** /

#ifndef __AIMLTEMPLATEELEMENT_H__
#define __AIMLTEMPLATEELEMENT_H__

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <map>
#include "strings.h"
#include "aimlelement.h"

using namespace std;
using namespace aiml;

namespace aiml {
    class TemplateElement : public AIMLElement {
    public:
        TemplateElement() {}
        TemplateElement(vector<TemplateElement*> elements);

        vector<TemplateElement*> getChildren();

        virtual string toString() = 0;
    private:
        vector<TemplateElement*> m_vtChildren;
    };
}

#endif

/ ********************************************** ******** /

这是课程That

#ifndef __AIMLTHAT_H__
#define __AIMLTHAT_H__

#include <iostream>
#include <ctime>
#include <cstdlib>
#include "aimltemplateelement.h"

using namespace std;

namespace aiml {
    class That : public TemplateElement {
    public:
        That() {}

        vector<string> elements();
    private:

    };
}

#endif

1 个答案:

答案 0 :(得分:0)

您需要检查空指针:

for (int i = 0, n = children.size(); i < n; i++) {
        if(children[i]) //Be sure that children[i] is not null before dereferencing it
        {
          string text = children[i]->toString();
          text = trim(text);
          vector<string> vsText = split(text);

          for(int j=0, m=vsText.size(); j<m; ++j) {
              elements.push_back(vsText[j]);
          }
       } 
    }

[编辑] 从你的评论我看到你所需要的只是在使用它之前初始化指向That的指针,顺便提一下,当你完成时不要忘记删除它:

That* that = new That();
that->elements();