C++ 使用列表STL进行测试时出现复制构造函数错误
以下代码发生运行时错误,这可能非常容易。 你能纠正一下吗 该代码用于测试带有列表的STL库 问题似乎源于两个函数:Test::Test(const Test&t)C++ 使用列表STL进行测试时出现复制构造函数错误,c++,copy-constructor,C++,Copy Constructor,以下代码发生运行时错误,这可能非常容易。 你能纠正一下吗 该代码用于测试带有列表的STL库 问题似乎源于两个函数:Test::Test(const Test&t) 和Test&Test::operator=(const Test&m) 我只想毫无差错地运行它 如果您确切知道问题发生的原因,请告诉我原因 //标题 class Test { public: int t; char *name; public: Test() { t = 1;
和Test&Test::operator=(const Test&m) 我只想毫无差错地运行它 如果您确切知道问题发生的原因,请告诉我原因 //标题
class Test
{
public:
int t;
char *name;
public:
Test() {
t = 1;
name = new char [strlen("test")+1];
strcpy(name, "ssss");
}
Test (int i) {
t = i;
}
Test(const Test& t);
~Test()
{
delete [] name;
}
Test& operator= (const Test& m);
char * get_name();
};
//实施
Test::Test(const Test& t)
{
this->t = t.t;
this->name = new char[strlen(t.name)+1];
strcpy(this->name, t.name);
}
Test& Test::operator= (const Test& m)
{
if(this == &m) return *this;
if(this->name != NULL) delete[] name;
name = new char[strlen(m.name)+1];
strcpy(this->name, m.name);
this->t = m.t;
return *this;
}
char * Test::get_name()
{
return name;
}
//主要功能
int main(int argc, const char * argv[])
{
Test a;
Test b(3);
Test c(4);
list <Test> t_list;
t_list.push_back(a);
t_list.push_back(b);
t_list.push_back(c);
list <Test>::iterator iter_begin = t_list.begin();
list <Test>::iterator iter_end = t_list.end();
for(; iter_begin != iter_end; iter_begin++)
{
printf("%d\n", iter_begin->t);
printf("%s\n", iter_begin->get_name());
}
list <Test> t_list2;
t_list2.push_back(c);
t_list2.push_back(b);
t_list2.push_back(a);
iter_begin = t_list2.begin();
iter_end = t_list2.end();
for(; iter_begin != iter_end; iter_begin++)
{
printf("%d\n", iter_begin->t);
printf("%s\n", iter_begin->get_name());
}
}
int main(int argc,const char*argv[]
{
试验a;
试验b(3);
试验c(4);
列表t_列表;
t_列表。向后推(a);
t_列表。向后推(b);
t_列表。推回(c);
列表::迭代器iter_begin=t_list.begin();
列表::迭代器iter_end=t_list.end();
for(;iter\u begin!=iter\u end;iter\u begin++)
{
printf(“%d\n”,iter\u begin->t);
printf(“%s\n”,iter\u begin->get\u name());
}
列表t_列表2;
t_列表2.向后推(c);
t_列表2.向后推(b);
t_list2.向后推(a);
iter_begin=t_list2.begin();
iter_end=t_list2.end();
for(;iter\u begin!=iter\u end;iter\u begin++)
{
printf(“%d\n”,iter\u begin->t);
printf(“%s\n”,iter\u begin->get\u name());
}
}
您的测试(int)
构造函数未初始化名称
。这导致了所有其他问题。(快速运行valgrind
会告诉您这一点。)纠正方法是使用std::string
。看看我的答案。