4、构造函数的调用规则.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //4、2、4 构造函数的调用规则
  2. //默认情况下,C++至少给一个类添加3个函数
  3. //?默认构造函数(无参,函数体为空)
  4. //?默认析构函数(无参,函数体为空)
  5. //?默认拷贝构造函数,对属性进行值拷贝
  6. //构造函数调用规则如下:
  7. //?如果用户定义有参构造函数,C++不再提供无参构造函数,但是会提供默认拷贝构造
  8. //?如果用户定义拷贝构造函数,C++不会再提供其他构造函数
  9. #if(0)
  10. #include <iostream>
  11. class Person
  12. {
  13. public:
  14. //Person()
  15. //{
  16. // std::cout << "Person的默认构造函数调用" << std::endl;
  17. //}
  18. Person(int age)
  19. {
  20. std::cout << "Person的有参构造函数调用" << std::endl;
  21. m_Age = age;
  22. }
  23. Person(const Person& p)
  24. {
  25. std::cout << "Person的拷贝构造函数调用" << std::endl;
  26. }
  27. ~Person()
  28. {
  29. std::cout << "Person的析构函数调用" << std::endl;
  30. }
  31. int m_Age;
  32. };
  33. //void test01()
  34. //{
  35. // Person p;
  36. // p.m_Age = 18;
  37. //
  38. // Person p2(p);
  39. //
  40. // std::cout << "p2的年龄为:" << p2.m_Age << std::endl;
  41. //
  42. //}
  43. void test02()
  44. {
  45. Person p(18);
  46. Person p2(p);
  47. }
  48. int main()
  49. {
  50. //test01();
  51. test02();
  52. system("pause");
  53. return 0;
  54. }
  55. #endif