C++深拷贝浅拷贝示例程序

2022/4/11 17:12:59

本文主要是介绍C++深拷贝浅拷贝示例程序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 1 #include <iostream>
 2 
 3 class String
 4 {
 5 private:
 6     char *m_BufMemPtr;
 7     int m_BufSize;
 8 
 9 public:
10     String(const char *srcbuf)
11     {
12         m_BufSize = strlen(srcbuf);
13         m_BufMemPtr = new char[m_BufSize + 1];
14         memcpy(m_BufMemPtr, srcbuf, m_BufSize);
15         m_BufMemPtr[m_BufSize] = '\0';
16     }
17     String(const String& str)
18     {
19         this->m_BufSize = str.m_BufSize;
20         this->m_BufMemPtr = new char[m_BufSize + 1];
21         memcpy(this->m_BufMemPtr, str.m_BufMemPtr, m_BufSize);
22         m_BufMemPtr[this->m_BufSize] = '\0';
23     }
24 
25     ~String()
26     {
27         delete[] m_BufMemPtr;
28     }
29 
30     friend std::ostream& operator<<(std::ostream& stream,const String& str);
31 };
32 
33 std::ostream& operator<<(std::ostream& stream, const String& str)
34 {
35     stream << str.m_BufMemPtr << std::endl;
36     return stream;
37 }
38 
39 int main()
40 {
41     String str1("hello world");
42     String str2 = str1;
43     std::cout << str1;
44     std::cout << str2;
45 }

 



这篇关于C++深拷贝浅拷贝示例程序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程