#include <iostream>
#include <vector>
using namespace std;class Test
{
public:
Test(int a)
{
m_a = a;
m_str = NULL;
m_str = new char[4];
if (m_str == NULL)
cout<<"invalid memory!"<<endl;
m_str = "abc";
cout<<"Constructor"<<endl;
} Test(Test &test)
{
this->m_a = test.m_a;
this->m_str = new char[4];
strcpy(this->m_str, test.m_str);
} ~Test()
{
int a = m_a;
if (m_str != NULL)
{
delete m_str;
m_str = NULL;
}
cout<<"Destructor"<<endl;
}
private:
int m_a;
char *m_str;
};int main()
{
Test t1(1);
Test t2 = t1;
return 0;
}
请问这个程序为什么崩溃,貌似delete m_str;的时候出错了。
#include <vector>
using namespace std;class Test
{
public:
Test(int a)
{
m_a = a;
m_str = NULL;
m_str = new char[4];
if (m_str == NULL)
cout<<"invalid memory!"<<endl;
m_str = "abc";
cout<<"Constructor"<<endl;
} Test(Test &test)
{
this->m_a = test.m_a;
this->m_str = new char[4];
strcpy(this->m_str, test.m_str);
} ~Test()
{
int a = m_a;
if (m_str != NULL)
{
delete m_str;
m_str = NULL;
}
cout<<"Destructor"<<endl;
}
private:
int m_a;
char *m_str;
};int main()
{
Test t1(1);
Test t2 = t1;
return 0;
}
请问这个程序为什么崩溃,貌似delete m_str;的时候出错了。
的问题
m_str = "abc"
改成
strcpy(m_str,"abc");
或
memcpy不过发现你好像没重写=操作符,难道这个没事
Test t2;
t2 = t1;
Test(Test &test) //这个也不是拷贝构造,const Test& test