zoukankan      html  css  js  c++  java
  • 直接初始化、拷贝初始化、拷贝赋值运算符

    1. #include<iostream>
    2. usingnamespace std;
    3. class MYCLASS
    4. {
    5. public:
    6. MYCLASS()=default;
    7. /*explicit*/ MYCLASS(string str): strValue(str)
    8. {
    9. cout <<"----MYCLASS(string str)"<< endl;
    10. }
    11. MYCLASS(int iValue): intValue(iValue)
    12. {
    13. cout <<"----MYCLASS(int iValue)"<< endl;
    14. }
    15. /**< 拷贝构造函数 */
    16. MYCLASS(const MYCLASS & myClass)
    17. {
    18. cout <<"----MYCLASS(const MYCLASS& myClass)"<< endl;
    19. strValue = myClass.strValue;
    20. }
    21. /**< 拷贝赋值运算符 */
    22. MYCLASS &operator=(const MYCLASS & myClass)
    23. {
    24. cout <<"----MYCLASS& operator=(const MYCLASS& myClass)"<< endl;
    25. this->intValue = myClass.intValue;
    26. this->strValue = myClass.strValue;
    27. return*this;
    28. }
    29. string getStrValue()
    30. {
    31. return strValue;
    32. }
    33. int getIntValue()
    34. {
    35. return intValue;
    36. }
    37. void setIntValue(int iValue)
    38. {
    39. intValue = iValue;
    40. }
    41. void setStrValue(string str)
    42. {
    43. strValue = str;
    44. }
    45. private:
    46. string strValue;
    47. int intValue;
    48. };
    49. int main()
    50. {
    51. /**< 当类的构造函数只有一个参数且该构造函数没有被explicit修饰时,可以直接用该参数类型的变量来给类对象赋值 */
    52. MYCLASS myClass1 = string("2014-11-25");
    53. /**
    54. * 首先调用MYCLASS(string str)生成一个临时的MYCLASS变量
    55. * 然后调用MYCLASS(const MYCLASS & myClass)将该临时变量赋值给myClass1
    56. * 由于编译器存在优化机制,所以这里会直接调用MYCLASS(string str)来初始化myClass1
    57. */
    58. //MYCLASS myClass2 = 100;
    59. MYCLASS myClass2 = myClass1;/**< 调用拷贝构造函数 */
    60. myClass2.setIntValue(100);
    61. myClass1 = myClass2;/**< 调用的是拷贝赋值运算符 */
    62. /**< 初始化类对象使用=时调用拷贝构造函数,当类对象创建完成之后使用=进行赋值时调用的是拷贝赋值运算符 */
    63. cout << myClass2.getStrValue()<<"--"<< myClass2.getIntValue()<< endl;
    64. return0;
    65. }
    66. /**
    67. * 输出结果:
    68. * ----MYCLASS(string str)
    69. * ----MYCLASS(const MYCLASS& myClass)
    70. * ----MYCLASS& operator=(const MYCLASS& myClass)
    71. * 2014-11-25--100
    72. */
     





  • 相关阅读:
    Innodb中自增长值的列
    LINUX-vmstat命令讲解
    find命令总结
    特殊权限chattr的用法
    openstack的最简单安装
    解决新电脑的系统安装问题:针对BIOS的UEFI模式
    Linux中安装字体
    云主机和vps的区别
    install-scp
    常见typedef 用法
  • 原文地址:https://www.cnblogs.com/fengkang1008/p/4652239.html
Copyright © 2011-2022 走看看