首页 > 编程语言 > 详细

C++类的基本函数(初级笔试一般用)

时间:2021-05-30 15:45:46      阅读:12      评论:0      收藏:0      [点我收藏+]

 

技术分享图片
 1 #include <iostream>
 2 class Tx
 3 {
 4 public:
 5 
 6 /* 默认私有类型 */
 7 Tx(const char * p = nullptr);//基本构造函数
 8 ~Tx();//析构函数
 9 Tx(const Tx& m);//拷贝构造函数
10 Tx& operator = (const Tx& m);//赋值函数
11 
12 /* 
13 c++11 后增加了新内容 其实是std::move的原理    默认合成好处就是可以不用你实现它
14 好处:减少资源的反复申请和释放    
15 */
16 Tx(Tx&& m)/* = default*/;//移动构造函数
17 Tx& operator=(Tx&& m)/* = default*/;//移动赋值函数,改变原来src值
18 //Tx& operator(const Tx&& m) = default;//移动赋值函数,不改变原来src值
19 
20 
21 char* t = nullptr;
22 };
23 
24 Tx::Tx(const char * p)
25 {
26 if (p == nullptr)
27 {
28 t = new char[1];
29 t[0] = 0;
30 }
31 
32 if (t != nullptr && strcmp(p , t) == 0)
33 return;
34 
35 Tx::~Tx();//懒人写法
36 t = new char[strlen(p) + 1];
37 strcpy(t, p);
38 }
39 
40 Tx::~Tx()
41 {
42 if(t != nullptr )
43 delete[]t;
44 t = nullptr;
45 }
46 
47 Tx::Tx(const Tx& m)
48 {
49 if (this == &m)
50 return ;
51 
52 Tx::~Tx();//懒人写法
53 t = new char[strlen(m.t) + 1];
54 strcpy(t, m.t);
55 }
56 
57 
58 Tx& Tx::operator=(const Tx& m)
59 {
60 if (this == &m)
61 return *this;
62 
63 Tx::~Tx();//懒人写法
64 t = new char[strlen(m.t) + 1];
65 strcpy(t, m.t);
66 return *this;
67 }
68 
69 Tx::Tx(Tx&& m)
70 {
71 if (this == &m)
72 return;
73 
74 Tx::Tx(m);//懒人写法
75 }
76 
77 Tx& Tx::operator=(Tx&& m)//如需要保留dest,可用const,
78 {
79 if (this == &m)//删除与否,随意扩展
80 return *this;
81 
82 Tx::~Tx();
83 t = m.t;
84 m.t = nullptr;
85 return *this;
86 }
87 
88  
89 
90 int main()
91 {
92 Tx x2 = Tx("123");
93 return 0;
94 }
View Code

 

C++类的基本函数(初级笔试一般用)

原文:https://www.cnblogs.com/archer-mowei/p/14827858.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!