• 关于CPP类中字符串成员初始化


    直接看代码吧

    1. #include
    2. #include
    3. /*
    4. A string is actually an object of the C++ Standard Library class string.
    5. This class is defined in header , and the name string, like cout, belongs to namespace std.
    6. To enable string-relative-statement compile, includes the header.
    7. The using directive in "using namespace std;" allows us to simply write string rather than std::string.
    8. For now, you can think of string variables like variables of other types such as int.
    9. The class template basic_string provides typical string-manipulation operations such as
    10. copying, searching, etc.
    11. The template definition and all support facilities are defined in namespace std;
    12. these include the typedef statement "typedef basic_string< char > string;"that creates the alias type string
    13. for basic_string. To use strings, include header .
    14. */
    15. using std::cout;
    16. using std::cin;
    17. using std::endl;
    18. using std::string;
    19. /*----------------------------------------------------*/
    20. class Cat
    21. {
    22. private:
    23. std::string _name = "Mogo";
    24. int _age = 20;
    25. public:
    26. Cat(string name)
    27. {
    28. if(name.length() < 5)
    29. _name = "hehda dsa You!";
    30. else
    31. _name = name;
    32. }
    33. //使用初始化列表通常是首选方法
    34. //因为它更高效,并且可以避免在构造函数体内对std::string等类型进行复制操作时产生的额外开销。
    35. Cat():_name("DanDan")
    36. {
    37. _age = 100;
    38. }
    39. Cat(int age):_name(4, 'Y'), _age(age) {}
    40. string shout(void)
    41. {
    42. return "my name is " + _name + " \"MI\"";
    43. }
    44. void show(void)
    45. {
    46. cout << "Age is: " << std::hex << _age << endl;
    47. }
    48. };
    49. /*----------------------------------------------------*/
    50. int main()
    51. {
    52. std::cout<<"Hello, World!"<
    53. Cat cat = Cat("Ista");
    54. Cat l_cat = Cat();
    55. Cat h_cat = Cat(255);
    56. cout << cat.shout() << endl;
    57. cout << l_cat.shout() << endl;
    58. cout << h_cat.shout() << endl;
    59. cat.show();
    60. l_cat.show();
    61. h_cat.show();
    62. string pre_firm("borgward");
    63. string rep_pos(8, 'X');
    64. cout << pre_firm << "---" << rep_pos << endl;
    65. return 0;
    66. }
    67. /*----------------------------------------------------*/

    运行结果:

    参考文章:

    C++类成员的初始化_c++ 类成员初始化-CSDN博客

    (完)

  • 相关阅读:
    Celery
    Nacos安装教程
    超赞极简奶油风装修攻略~速来抄作业
    Python的Numpy库的ndarray对象常用构造方法及初始化方法
    H743 USBHOST协议栈 CPU占用率高的问题。
    Leetcode 940. 不同的子序列 II
    vue项目使用vue-video-player实现视频直播功能
    使用go-redis/redis依赖操作redis
    VHDL基础知识笔记(2)
    通过zookeeper浅谈一致性算法
  • 原文地址:https://blog.csdn.net/lm393485/article/details/138160993