访问向量类成员时出现分段错误



我在 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

您需要检查空指针:

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();

相关内容

  • 没有找到相关文章