C++ STL中的分割错误
我在使用STL库时遇到了问题。我附上代码片段C++ STL中的分割错误,c++,stl,polymorphism,segmentation-fault,C++,Stl,Polymorphism,Segmentation Fault,我在使用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"<&l
// 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();
}
//将类对象存储在向量中。
#包括
#包括
使用名称空间std;
班级家长{
int-id;
公众:
父(){};
父(int x){id=x;}
virtual~Parent(){cout正如@UncleBens在评论中所写,New_class
违反了规则
我个人的建议是不要使用动态分配的属性…正如@UncleBens在评论中写道的那样,New_class
违反了规则
我个人的建议是不要使用动态分配的属性…您的new2构造函数将临时对象的副本推送到tp2向量上
然后销毁临时对象并删除其tp指针。因此,向量中的副本现在有一个指向已释放内存的tp指针
您的新类应该实现一个复制构造函数。您的新2构造函数将临时对象的副本推送到tp2向量上
然后销毁临时对象并删除其tp指针。因此,向量中的副本现在有一个指向已释放内存的tp指针
你的新类应该实现一个复制构造函数。你忘了在你的新类上定义复制构造函数和赋值运算符。我们一直看到这一点。这是新手要克服的基本障碍,它吸引了大多数人
将项添加到向量时,会隐式调用复制构造函数,但编译器生成的版本不适合新的_类,因此必须编写自己的
对于给定的其他代码,很难给出复制构造函数和赋值操作符的合理定义,所以我不打算尝试。建议您在一本好的C++书中读到它。
您忘记在NexHype类中定义复制构造函数和赋值操作符。我们一直在看到这一点。新手要克服这一点是一个基本障碍。而且它吸引了大多数人
将项添加到向量时,会隐式调用复制构造函数,但编译器生成的版本不适合新的_类,因此必须编写自己的
很难给出对你的其他代码的复制构造函数和赋值操作符的合理定义,所以我不会尝试。建议你在一本好的C++书籍中读到它。< /P>你遇到了什么问题?仅仅是违反了三的规则:你遇到了什么问题?仅仅是违反了三的规则: