#include<iostream>
#include<string>
class string
{
private:
char* m_buffer;
unsigned int m_size;
public:
string(const char* string)
{
m_size = strlen(string);
//m_buffer = new char[m_size];
//memcpy(m_buffer, string, m_size );没有添加终止符错误示范
m_buffer = new char[m_size + 1];
memcpy(m_buffer, string, m_size + 1);//带入终止字符
//m_buffer[m_size] = 0;同添加终止符同一类操作
}
string(const string& other)
:m_size(other.m_size)
{
std::cout << "copied string" << std::endl;
m_buffer = new char[m_size + 1];
memcpy(m_buffer, other.m_buffer, m_size+1);
}
~string()
{
delete[]m_buffer;
}
char& operator[](unsigned int index)
{
return m_buffer[index];
}
friend std::ostream& operator << (std::ostream& stream, const string& string);//借用友元来访问类的私有成员
};
std::ostream& operator << (std::ostream& stream, const string& string)
{
stream << string.m_buffer;
return stream;
}
//深拷贝复制整个对象
void printstring(const string& string)
{
std::cout << string << std::endl;
}
int main()
{
string string1 = "cherno";
string string2 = string1;//浅拷贝对象buffer内存地址相同程序崩溃,程序试图两次构析释放同一个模块空间
string2[2] = 'a';
printstring(string1);
printstring(string2);
std::cin.get();
}
c++浅拷贝,深拷贝
最新推荐文章于 2024-11-12 15:18:48 发布