类对象作为类成员

C++类中的成员可以是另一个类的对象,我们称该成员为 对象成员
例如:

  1. class A {}
  2. class B
  3. {
  4. A a
  5. }

B类中有对象A作为成员,A为对象成员
那么当创建B对象时,A与B的构造和析构的顺序是谁先谁后?
示例:

  1. class Phone
  2. {
  3. public:
  4. Phone(string name)
  5. {
  6. m_PhoneName = name;
  7. cout << "Phone构造" << endl;
  8. }
  9. ~Phone()
  10. {
  11. cout << "Phone析构" << endl;
  12. }
  13. string m_PhoneName;
  14. };
  15. class Person
  16. {
  17. public:
  18. //初始化列表可以告诉编译器调用哪一个构造函数
  19. Person(string name, string pName) :m_Name(name), m_Phone(pName)
  20. {
  21. cout << "Person构造" << endl;
  22. }
  23. ~Person()
  24. {
  25. cout << "Person析构" << endl;
  26. }
  27. void playGame()
  28. {
  29. cout << m_Name << " 使用" << m_Phone.m_PhoneName << " 牌手机! " << endl;
  30. }
  31. string m_Name;
  32. Phone m_Phone;
  33. };
  34. void test01()
  35. {
  36. //当类中成员是其他类对象时,我们称该成员为 对象成员
  37. //构造的顺序是 :先调用对象成员的构造,再调用本类构造
  38. //析构顺序与构造相反
  39. Person p("张三" , "苹果X");
  40. p.playGame();
  41. }
  42. int main() {
  43. test01();
  44. system("pause");
  45. return 0;
  46. }
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. class Phone {
  5. public:
  6. Phone(string initPhoneName):phoneName(initPhoneName) {};
  7. string phoneName;
  8. };
  9. class Person {
  10. public:
  11. Person(string initPersonName, string initPhoneName) :personName(initPersonName), phone(initPhoneName) {};
  12. string personName;
  13. Phone phone;
  14. };
  15. void example() {
  16. Person p("John", "iPhone");
  17. cout << p.personName << " has a(an) " << p.phone.phoneName << endl;;
  18. }
  19. int main()
  20. {
  21. example();
  22. }

在java的控制台输出中有这样的语句:

  1. System.out.println("Hello World!");

而利用面向对象编程思想中的类嵌套我们就可以在C++中实现这样的风格。

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. class output {
  5. public:
  6. output() {};
  7. void println(string STD_OUT) {
  8. cout << STD_OUT << endl;
  9. }
  10. void print(string STD_OUT) {
  11. cout << STD_OUT;
  12. };
  13. };
  14. class Sysfunc {
  15. public:
  16. Sysfunc(){}
  17. output out;
  18. };
  19. void example() {
  20. Sysfunc System;
  21. System.out.println("Hello World!");
  22. cout << "This is how the Java's OUTPUT looks like" << endl;
  23. System.out.print("Hello World!");
  24. }
  25. int main()
  26. {
  27. example();
  28. //In java, we have a hello world program
  29. //System.out.println("Hello World!");
  30. }