2011-08-10 179 views
0

我遇到了使用STL库的问题。我附上了代码片段。使用STL时出现分段错误

// Store a class object in a vector. 
#include <iostream> 
#include <vector> 

using namespace std; 

class Parent{ 
    int id; 
public: 
    Parent(){}; 
    Parent(int x){ id=x;} 
    virtual ~Parent(){ cout<<"Parent"<<endl;} 
    virtual void print3(){cout<<"Printing Parent "<<id;} 
}; 

class Child:public Parent{ 
    int c; 
public: 
    Child(int m,int n):Parent(m){ 
    c=n; 
    } 
    Child(){c=0;} 
    virtual ~Child(){ cout<<"Child"<<endl;} 
    virtual void print3(){cout<<"Printing Child "<<c;} 
}; 

class New_class 
{ 
public: 
    New_class(){ 
    tp=new Child(10,20); 
    } 
    ~New_class(){ 
    delete tp; 
    } 
    void check(Parent &tmp){ 
    tmp.print3(); 
    } 
    void print2(){tp->print3();} 
private: 
    Parent *tp; 

}; 

class New2{ 
    vector<New_class> tp2; 
public: 
    New2(){ 
    tp2.push_back(New_class()); 
    } 
    ~New2(){ 
     tp2.clear(); 
    } 
    void print(){ vector<New_class>::iterator it=tp2.begin(); (*it).print2();} 
}; 

int main() 
{ 
    New2 m ; 
    m.print(); 
} 

在此先感谢。 Regards

+0

你有什么问题? –

+3

只是违反三规则:http://stackoverflow.com/questions/4172722/what-is-the-rule-of-reeree – UncleBens

+0

@Dean:'New_class' –

回答

3

由于@UncleBens在评论中写道,New_class违反了rule of three

我个人的建议是不要使用动态分配的属性...

+0

1号线是很好的建议。 2号线是伟大的建议。 –

2

你NEW2构造推的临时对象的副本到TP2载体。

临时对象然后被销毁并删除它的tp指针。因此,向量中的副本现在有一个指向已被释放的内存的tp指针。

你的New_class应该实现一个拷贝构造函数。

0

你忘了在你的New_class上定义拷贝构造函数和赋值操作符。我们一直都在看。这是新手克服困难的基本障碍,它吸引了大多数人。

复制构造函数在将项添加到向量时隐式调用,但编译器生成的版本不适合您的New_class,因此您必须编写自己的。

给出你的其他代码很难给出复制构造函数和赋值运算符的合理定义,所以我不打算试试。建议你阅读一本好的C++书。