深拷贝
带有指针的类,必须有 拷贝构造和拷贝赋值构造函数。
MyString.hpp
#include <iostream>
class myString
{
public:
myString(const char* cstr = nullptr);
myString(const myString& str);
myString& operator=(const myString &);
~ myString();
char* get_c_char()const{return m_data;};
private:
int m_len;
char *m_data;
};
MyString.cpp
#include <iostream>
#include <cstring>
#include "myString.hpp"
using namespace std;
myString::myString(const char* cstr)
{
cout << "normal construct" << endl;
if(cstr!=nullptr)
{
m_len = strlen(cstr);
m_data = new char[m_len + 1]{0};
strncpy_s(m_data, sizeof(m_data), cstr, m_len);
cout<< m_data << endl;
}
else
{
m_data = new char[1];
*m_data = '\0';
}
}
myString::~myString()
{
cout << "De-constructer called" << endl;
delete[] m_data;
m_data = nullptr;
}
myString::myString(const myString& str)
{
cout << "copy construct called" << endl;
m_len = strlen(str.m_data);
m_data = new char[m_len+1]{0};
strncpy_s(m_data, sizeof(m_data), str.m_data, m_len);
cout << m_data << endl;
}
myString& myString::operator=(const myString& str)
{
cout << "operator= construct called" << endl;
if(this == &str)
{
return *this;
}
delete[] m_data;
m_data = new char[strlen(str.m_data)+1]{0};
strncpy_s(m_data, sizeof(m_data), str.m_data, strlen(str.m_data));
return *this;
}
main.c
#include <iostream>
#include "myString.hpp"
int main()
{
std::cout<< "hello" <<std::endl;
char s1[]="string1";
char s2[]="string2";
myString mstr1(s1);
myString mstr2(s2);
mstr2 = mstr1;
std::cout << mstr2.get_c_char() << std::endl;
myString mstr3(mstr2);
std::cout << mstr3.get_c_char() << std::endl;
}
|