• c++——构造函数, 析构函数,拷贝构造函数,赋值运算符重载,const成员


    一.构造函数

    1.构造函数是一个特殊的成员函数,名字与类名相同,创建类类型对象时由编译器自动调用,以保证每个数据成 员都有 一个合适的初始值,并且在对象整个生命周期内只调用一次

    2.作用:初始化对象。

    3.特性:

    (1). 函数名与类名相同。

    (2). 无返回值。

    (3). 对象实例化时编译器自动调用对应的构造函数。

    (4). 构造函数可以重载。

    1. #include
    2. using namespace std;
    3. class lin
    4. {
    5. public:
    6. // 1.无参构造函数
    7. lin()
    8. {
    9. cout << "lin1" << endl;
    10. }
    11. // 2.带参构造函数
    12. lin(int year, int month, int day)
    13. {
    14. _year = year;
    15. _month = month;
    16. _day = day;
    17. cout << "lin2" << endl;
    18. }
    19. private:
    20. int _year;
    21. int _month;
    22. int _day;
    23. };
    24. void Testlin()
    25. {
    26. lin d1; // 调用无参构造函数
    27. lin d2(2022, 8, 10); // 调用带参的构造函数
    28. lin d3();//如果通过无参构造函数创建对象时,对象后面不用跟括号,否则就成了函数声明
    29. }
    30. int main()
    31. {
    32. Testlin();
    33. return 0;
    34. }

     4. 如果类中没有显式定义构造函数,则C++编译器会自动生成一个无参的默认构造函数,一旦用户显式定 义编译器将不再生成。

    1. #include
    2. using namespace std;
    3. class lin
    4. {
    5. public:
    6. /*
    7. // 如果用户显式定义了构造函数,编译器将不再生成
    8. lin(int year, int month, int day)
    9. {
    10. _year = year;
    11. _month = month;
    12. _day = day;
    13. }
    14. */
    15. void Print()
    16. {
    17. cout << _year << "-" << _month << "-" << _day << endl;
    18. }
    19. private:
    20. int _year;
    21. int _month;
    22. int _day;
    23. };
    24. int main()
    25. {
    26. // 将lin类中构造函数屏蔽后,代码可以通过编译,因为编译器生成了一个无参的默认构造函数
    27. // 将lin类中构造函数放开,代码编译失败,因为一旦显式定义任何构造函数,编译器将不再生成
    28. lin d;
    29. //lin d1(1);// 没有合适的默认构造函数可用
    30. d.Print();
    31. return 0;
    32. }

     

     5.:C++11 中针对自定义类型初始化,内置类型成员不初始化的缺陷,又打了补丁,即:内置类型成员变量在类中声明时 可以给默认值。

    6.无参的构造函数和全缺省的构造函数都称为默认构造函数,并且默认构造函数只能有一个。注意:无参 构造函数、全缺省构造函数、我们没写编译器默认生成的构造函数,都可以认为是默认构造函数。

    1. #include
    2. using namespace std;
    3. class lin
    4. {
    5. public:
    6. /*lin()
    7. {
    8. _year = 2022;
    9. _month = 8;
    10. _day = 10;
    11. cout << "lin1 " << _year <<"/" << month<<"/" << day << endl;
    12. }*/
    13. lin(int year = 2022, int month = 8, int day = 10)
    14. {
    15. _year = year;
    16. _month = month;
    17. _day = day;
    18. cout << "lin2 " << _year <<"/" << month<<"/" << day << endl;
    19. }
    20. private:
    21. int _year;
    22. int _month;
    23. int _day;
    24. };
    25. int main()
    26. {
    27. lin d;
    28. return 0;
    29. }

    二.析构函数

    1.概念:与构造函数功能相反,析构函数不是完成对对象本身的销毁,局部对象销毁工作是由编译器完成 的。而对象在销毁时会自动调用析构函数,完成对象中资源的清理工作。

    2.特性

    (1). 析构函数名是在类名前加上字符 ~。

    (2). 无参数无返回值类型。

    (3). 一个类只能有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。

    (4)析构函数不能重载

    (5). 对象生命周期结束时,C++编译系统系统自动调用析构函数。

    1. #include
    2. using namespace std;
    3. typedef int DataType;
    4. class Stack
    5. {
    6. public:
    7. Stack(size_t capacity = 3)
    8. {
    9. _a = (DataType*)malloc(sizeof(DataType) * capacity);
    10. if (NULL == _a)
    11. {
    12. perror("malloc申请空间失败:");
    13. return;
    14. }
    15. _capacity = capacity;
    16. _size = 0;
    17. }
    18. void Push(DataType data)
    19. {
    20. _a[_size] = data;
    21. _size++;
    22. }
    23. ~Stack()
    24. {
    25. if (_a)
    26. {
    27. free(_a);
    28. _a = NULL;
    29. _capacity = 0;
    30. _size = 0;
    31. }
    32. cout << "~Stack()" << endl;
    33. }
    34. private:
    35. DataType* _a;
    36. int _capacity;
    37. int _size;
    38. };
    39. int main()
    40. {
    41. Stack s;
    42. s.Push(1);
    43. s.Push(2);
    44. }

    三.拷贝构造函数

    1.概念:只有单个形参,该形参是对本类类型对象的引用(一般常用const修饰),在用已存在的类类型 对象创建新对象时由编译器自动调用 

    2.特性:

    (1). 拷贝构造函数是构造函数的一个重载形式。

    (2). 拷贝构造函数的参数只有一个且必须是类类型对象的引用,使用传值方式编译器直接报错,因为会引发 无穷递归调用。

    1. #include
    2. using namespace std;
    3. class lin
    4. {
    5. public:
    6. lin(int year = 2022, int month = 8, int day = 10)
    7. {
    8. _year = year;
    9. _month = month;
    10. _day = day;
    11. }
    12. // lin(const lin d) // 错误写法:编译报错,会引发无穷递归
    13. lin(const lin& d) // 正确写法
    14. {
    15. _year = d._year;
    16. _month = d._month;
    17. _day = d._day;
    18. }
    19. private:
    20. int _year;
    21. int _month;
    22. int _day;
    23. };
    24. int main()
    25. {
    26. lin d1;
    27. lin d2(d1);
    28. return 0;
    29. }

    3.若未显式定义,编译器会生成默认的拷贝构造函数。 默认的拷贝构造函数对象按内存存储按字节序完成拷贝,这种拷贝叫做浅拷贝,或者值拷贝,内置类型是按照字节方式直接拷贝的,而自定义类型是调 用其拷贝构造函数完成拷贝的。

    4.:类中如果没有涉及资源申请时,拷贝构造函数是否写都可以;一旦涉及到资源申请时,则拷贝构 造函数是一定要写的,否则就是浅拷贝,为了提高程序效率,一般对象传参时,尽量使用引用类型,返回时根据实际场景,能用引用尽量使用引 用。

    5.拷贝构造函数典型调用场景:

    (1).使用已存在对象创建新对象

    (2)函数参数类型为类类型对象

    (3)函数返回值类型为类类型对象

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. Date(int year, int minute, int day)
    7. {
    8. cout << "Date(int,int,int):" << this << endl;
    9. }
    10. Date(const Date& d)
    11. {
    12. cout << "Date(const Date& d):" << this << endl;
    13. }
    14. ~Date()
    15. {
    16. cout << "~Date():" << this << endl;
    17. }
    18. private:
    19. int _year;
    20. int _month;
    21. int _day;
    22. };
    23. Date Test(Date d)
    24. {
    25. Date temp(d);//调用拷贝构造函数创建temp
    26. return temp;//函数以值方式返回,返回时使用temp拷贝构造临时对象来返回
    27. }
    28. int main()
    29. {
    30. Date d1(2022, 8, 10);//调用构造函数创建的d1
    31. Test(d1);//Test以值传递的方式传参时调用拷贝构造函数创建d
    32. return 0;
    33. }

     四..赋值运算符重载

    1.概念:C++为了增强代码的可读性引入了运算符重载,运算符重载是具有特殊函数名的函数,也具有其返回值类型,函数名字以及参数列表,其返回值类型与参数列表与普通的函数类似。 函数名字为:关键字operator后面接需要重载的运算符符号。

    2.函数原型:返回值类型 operator操作符(参数列表)

    3.注意:

    (1) 不能通过连接其他符号来创建新的操作符:比如operator@

    (2) 重载操作符必须有一个类类型参数

    (3) 用于内置类型的运算符,其含义不能改变,例如:内置的整型+,不 能改变其含义

    (4) 作为类成员函数重载时,其形参看起来比操作数数目少1,因为成员函数的第一个参数为隐藏的this

    (5) (.*)( ::)( sizeof)(  ?)( :  .) 注意以上5个运算符不能重载。

    4.赋值运算符重载格式:

    (1)参数类型:const T&,传递引用可以提高传参效率

    (2)返回值类型:T&,返回引用可以提高返回的效率,有返回值目的是为了支持连续赋值

    (3)检测是否自己给自己赋值

    (4)返回*this :要复合连续赋值的含义

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. Date(int year = 2022, int month = 8, int day = 10)
    7. {
    8. _year = year;
    9. _month = month;
    10. _day = day;
    11. }
    12. Date(const Date& d)
    13. {
    14. _year = d._year;
    15. _month = d._month;
    16. _day = d._day;
    17. }
    18. Date& operator=(const Date& d)
    19. {
    20. //检查是否为自己为自己赋值
    21. if (this != &d)
    22. {
    23. _year = d._year;
    24. _month = d._month;
    25. _day = d._day;
    26. }
    27. return *this;
    28. }
    29. private:
    30. int _year;
    31. int _month;
    32. int _day;
    33. };
    34. int main()
    35. {
    36. return 0;
    37. }

    5.赋值运算符只能重载成类的成员函数不能重载成全局函数

    1. class Date
    2. {
    3. public:
    4. Date(int year = 1900, int month = 1, int day = 1)
    5. {
    6. _year = year;
    7. _month = month;
    8. _day = day;
    9. }
    10. int _year;
    11. int _month;
    12. int _day;
    13. };
    14. // 赋值运算符重载成全局函数,注意重载成全局函数时没有this指针了,需要给两个参数
    15. Date& operator=(Date& left, const Date& right)
    16. {
    17. if (&left != &right)
    18. {
    19. left._year = right._year;
    20. left._month = right._month;
    21. left._day = right._day;
    22. }
    23. return left;
    24. }
    25. // 编译失败:
    26. // error C2801: “operator =”必须是非静态成员

    原因:赋值运算符如果不显式实现,编译器会生成一个默认的。此时用户再在类外自己实现一个全局的赋值运算符重载,就和编译器在类中生成的默认赋值运算符重载冲突了,故赋值运算符重载只能是类的成员函数。

    6.用户没有显式实现时,编译器会生成一个默认赋值运算符重载,以值的方式逐字节拷贝。注意:内置类型成员变量是直接赋值的,而自定义类型成员变量需要调用对应类的赋值运算符重载完成赋值。

    7.日期类的实现

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. // 获取某年某月的天数
    7. int GetMonthDay(int year, int month)const
    8. {
    9. static int monthday[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
    10. if ((month == 2)
    11. && (_year % 4 == 0 || _year % 100 != 0) && (_year % 400 == 0))
    12. {
    13. return 29;
    14. }
    15. return monthday[month];
    16. }
    17. // 全缺省的构造函数
    18. Date(int year = 1900, int month = 1, int day = 1)
    19. {
    20. if (year >= 0
    21. && month >= 1 && month <= 12
    22. && day >= 1 && day <= GetMonthDay(year, month))
    23. {
    24. _year = year;
    25. _month = month;
    26. _day = day;
    27. }
    28. else
    29. {
    30. cout<<"日期有误"<
    31. }
    32. }
    33. // 拷贝构造函数
    34. Date(const Date& d)
    35. {
    36. this->_year = d._year;
    37. this->_month = d._month;
    38. this->_day = d._day;
    39. }
    40. // 赋值运算符重载
    41. // d2 = d3 -> d2.operator=(&d2, d3)
    42. Date& operator=(const Date& d)
    43. {
    44. if (this != &d)
    45. {
    46. this->_year = d._year;
    47. this->_month = d._month;
    48. this->_day = d._day;
    49. }
    50. return *this;
    51. }
    52. // 日期+=天数
    53. Date& operator+=(int day)
    54. {
    55. if (day < 0)
    56. {
    57. return *this -= -day;
    58. }
    59. _day += day;
    60. while (day > GetMonthDay(_year, _month))
    61. {
    62. _day -= GetMonthDay(_year, _month);
    63. ++_month;
    64. if (_month == 13)
    65. {
    66. _year++;
    67. _month = 1;
    68. }
    69. }
    70. return *this;
    71. }
    72. // 日期+天数
    73. Date operator+(int day)const
    74. {
    75. Date tmp(*this);
    76. tmp += day;
    77. return tmp;
    78. }
    79. // 日期-天数
    80. Date operator-(int day)const
    81. {
    82. Date tmp(*this);
    83. tmp -= day;
    84. return tmp;
    85. }
    86. // 日期-=天数
    87. Date& operator-=(int day)
    88. {
    89. if (day < 0)
    90. {
    91. return *this += -day;
    92. }
    93. _day -= day;
    94. while(_day<=0)
    95. {
    96. _month--;
    97. if (_month == 0)
    98. {
    99. _year--;
    100. _month = 12;
    101. }
    102. _day+= GetMonthDay(_year, _month);
    103. }
    104. return *this;
    105. }
    106. // 前置++
    107. Date& operator++()
    108. {
    109. return *this += 1;
    110. }
    111. // 后置++
    112. Date operator++(int)
    113. {
    114. Date tmp(*this);
    115. *this += 1;
    116. return tmp;
    117. }
    118. // 后置--
    119. Date operator--(int)
    120. {
    121. Date tmp(*this);
    122. *this -= 1;
    123. return tmp;
    124. }
    125. // 前置--
    126. Date& operator--()
    127. {
    128. return *this -= 1;
    129. }
    130. // >运算符重载
    131. bool operator>(const Date& d)const
    132. {
    133. if (_year > d._year)
    134. {
    135. return true;
    136. }
    137. else if (_year == d._year)
    138. {
    139. if (_month > d._month)
    140. {
    141. return true;
    142. }
    143. else if (_month == d._month&&_day>d._day)
    144. {
    145. return true;
    146. }
    147. }
    148. return false;
    149. }
    150. // ==运算符重载
    151. bool operator==(const Date& d)const
    152. {
    153. return ((_year == d._year) && (_month == d._month) && (_day == d._day));
    154. }
    155. // >=运算符重载
    156. bool operator >= (const Date& d) const
    157. {
    158. return (*this > d) || (*this == d);
    159. }
    160. // <运算符重载
    161. bool operator < (const Date& d)const
    162. {
    163. return !(*this >= d);
    164. }
    165. // <=运算符重载
    166. bool operator <= (const Date& d)const
    167. {
    168. return !(*this > d);
    169. }
    170. // !=运算符重载
    171. bool operator != (const Date& d)const
    172. {
    173. return !(*this == d);
    174. }
    175. // 日期-日期 返回天数
    176. int operator-(const Date& d)const
    177. {
    178. //定义一个flag用来判断运算后的符号为+-
    179. int flag = 1;
    180. Date max = *this;
    181. Date min = d;
    182. if (*this < d)
    183. {
    184. max = d;
    185. min = *this;
    186. flag = -1;
    187. }
    188. //统计日期之间相差的天数
    189. int day = 0;
    190. while (min < max)
    191. {
    192. ++(min);
    193. ++(day);
    194. }
    195. return day * flag;
    196. }
    197. void Print()
    198. {
    199. cout << _year << "/" << _month << "/" << _day << endl;
    200. }
    201. private:
    202. int _year;
    203. int _month;
    204. int _day;
    205. };
    206. int main()
    207. {
    208. Date lin(2022, 8, 12);
    209. lin.Print();
    210. Date lin1 = lin + 10;
    211. lin1.Print();
    212. Date lin2(2022, 8, 10);
    213. cout << "lin == lin2"<<" " << (lin == lin2) << endl;
    214. cout << "lin > lin2" << " " << (lin > lin2) << endl;
    215. cout << "lin < lin2" << " " << (lin < lin2) << endl;
    216. return 0;
    217. }

     五:const成员

    1.将const修饰的“成员函数”称之为const成员函数,const修饰类成员函数,实际修饰该成员函数隐含的this 指针,表明在该成员函数中不能对类的任何成员进行修改。

    1. #include
    2. using namespace std;
    3. class Date
    4. {
    5. public:
    6. Date(int year, int month, int day)
    7. {
    8. _year = year;
    9. _month = month;
    10. _day = day;
    11. }
    12. void Print()
    13. {
    14. cout << "Print()" << endl;
    15. cout << "year:" << _year << endl;
    16. cout << "month:" << _month << endl;
    17. cout << "day:" << _day << endl << endl;
    18. }
    19. void Print() const
    20. {
    21. cout << "Print()const" << endl;
    22. cout << "year:" << _year << endl;
    23. cout << "month:" << _month << endl;
    24. cout << "day:" << _day << endl << endl;
    25. }
    26. private:
    27. int _year;
    28. int _month;
    29. int _day;
    30. };
    31. void Test()
    32. {
    33. Date d1(2022, 8, 10);
    34. d1.Print();
    35. const Date d2(2022, 8, 10);
    36. d2.Print();
    37. }
    38. int main()
    39. {
    40. Test();
    41. return 0;
    42. }

     2.取地址及const取地址操作符重载

    1. class Date
    2. {
    3. public :
    4. Date* operator&()
    5. {
    6. return this ;
    7. }
    8. const Date* operator&()const
    9. {
    10. return this ;
    11. }
    12. private :
    13. int _year ; // 年
    14. int _month ; // 月
    15. int _day ; // 日
    16. };

    这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需要重载,比 如想让别人获取到指定的内容!

  • 相关阅读:
    DevOps的出现带来的变化
    纳米银和巯基共修饰SiO2包裹Fe3O4磁性微球/空腔型Fe3O4@mSiO2-AuNCs复合微球制备方法
    多线程-线程池
    纯css就能实现可点击切换的轮播图,feel起来很丝滑
    新移动时代内容制作呈现与开发利器-Zoomla!逐浪CMS v8.6.2发布
    小程序也能是App中的引流神器?
    【MATLAB】求解含有三角函数的方程
    yhtest
    变量、常量以及与其他语言的差异 - Go语言从入门到实战
    C++项目实战-UDP服务器
  • 原文地址:https://blog.csdn.net/qq_64425854/article/details/126266586