2015-10-15 45 views
0

我試圖在Element類中包含一個指針向量。所以Element對象將包含子元素。 錯誤是「信號接收的:SIGSEGV(段錯誤)」在此行中發生 錯誤「串test44 = test333 [0] - > GetVElement();」C++ NetBeans錯誤獲取指針的子向量中元素的字符串值

我假定任一所述元件對象是沒有推回去,或者獲取子向量的代碼是錯誤的。

代碼張貼如下。如果你需要其他東西,請告訴我。

Element.cpp --------------------

Element::Element() { 
    this->vLineNo = -1; 
    this->vElement = " "; 
    this->vContent = " "; 
    vector<Element*> temp; 
    this->ChildElementVctr = temp; 
} 

//4 parameter constructor 
Element::Element(int lineno, string vElement, string vContent,vector<Element*> vVector){ 
    this->vLineNo = lineno; 
    this->vElement = vElement; 
    this->vContent = vContent; 
    this->ChildElementVctr = vVector; 
} 

void Element::SetChildElementVctr(vector<Element*> ChildElementVctr) { 
    this->ChildElementVctr = ChildElementVctr; 
} 

vector<Element*> Element::GetChildElementVctr() const { 
    return ChildElementVctr; 
} 

Main.cpp的------------- ----

vector<Element*> TestVector; 

Element* obj_Element = new Element(); 
    obj_Element->SetVLineNo(1); // calls setter function of the class Element to assign Line number 
    obj_Element->SetVElement("TestElement"); // calls setter function of the  class Element to assign Element tag name 
    obj_Element->SetVContent("TestContent"); 

    Attribute* obj_Attribute = new Attribute(); 
    obj_Attribute->SetVName("AttributeName"); 
    obj_Attribute->SetVValue("AttributeValue"); 
    obj_Element->GetAttributeVctr().push_back(obj_Attribute); 

    TestVector.push_back(obj_Element); 
    TestVector[0]->GetChildElementVctr().push_back(obj_Element); //push back the elemenet object to the Child Element Vector 
    string test11 = TestVector[0]->GetVElement(); 
    vector<Element*> test333 = TestVector[0]->GetChildElementVctr(); //gets the vector of pointers of Child elements 
    string test44 = test333[0]->GetVElement(); //ERROR occurs here 

element.h展開---

class Element { 
public: 

    Element(); 
    Element(int lineno, string vElement,string vContent, vector<Element*> vVector); 
    Element(const Element& orig); 

    void SetChildElementVctr(vector<Element*> ChildElementVctr); 
    vector<Element*> GetChildElementVctr() const; 

private: 
    int vLineNo ; 
    string vElement; 
    string vContent; 
    vector<Element*> ChildElementVctr; 
    vector<Attribute*> AttributeVctr; 

回答

0

你的功能

vector<Element*> Element::GetChildElementVctr() const { 
    return ChildElementVctr; 
} 

按值返回一個向量。它複製你的會員矢量。無論你用它做什麼,都不會影響你的班級成員。當你push_back()元素,你推他們到副本。當你以後訪問成員矢量的第一個元素(或者,確切地說,是它的另一個副本)時,最終可以訪問不存在的元素。

要解決該問題,擺脫你的存取功能,使矢量類的公共成員(現在我要求downvotes!)

+1

謝謝主席先生。你今天教我新東西。 – AskAround