对象数组

对象数组的定义与访问

  • 定义对象数组

类名 数组名[元素个数];

  • 访问对象数组元素

通过下标访问
数组名[下标].成员名

对象数组初始化

  • 数组中每一个元素对象被创建时,系统都会调用类构造函数初始化该对象。
  • 通过初始化列表赋值。

例:Point a[2]={Point(1,2),Point(3,4)};

  • 如果没有为数组元素指定显式初始值,数组元素便使用默认值初始化(调用默认构造函数)。
  • 声明一个数组对象,有两种方法

方法1:

  1. Employee emp[5]={
  2. Employee("Zhang San", "Haidian", "Beijing"),
  3. Employee("Li Si", "Xuanwu", "Beijing"),
  4. Employee("Wang Wu", "Nanfu", "Shanghai"),
  5. Employee("Zhu Ge", "Wuhou", "Chengdu"),
  6. Employee("Sun ying", "Zhifu", "Yantai")};

方法2(动态申请内存,类似C#和Java那种写法)

  1. Employee *emp1st = new Employee("Li Si", "Xuanwu", "Beijing");//定义一个指针变量emp1st
  2. emp[0] = *emp1st;//指针所指的对象返回给数组
  3. delete emp1st;//释放内存


数组元素所属类的构造函数

  • 元素所属的类不声明构造函数,则采用默认构造函数。
  • 各元素对象的初值要求为相同的值时,可以声明具有默认形参值的构造函数。
  • 各元素对象的初值要求为不同的值时,需要声明带形参的构造函数。
  • 当数组中每一个对象被删除时,系统都要调用一次析构函数。

实例代码

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. int Client::ClientNum = 0;
  5. char Client::ServerName = 'a';
  6. class Employee {
  7. private:
  8. string name;
  9. string streeName;
  10. string city;
  11. public:
  12. Employee(string n, string s, string c) {
  13. name = n;
  14. streeName = s;
  15. city = c;
  16. };
  17. Employee(){
  18. name ="";
  19. streeName ="";
  20. city ="";
  21. };
  22. void display();
  23. string chane_name(string n);
  24. };
  25. void Employee::display(){
  26. cout << name << streeName << city<<endl;
  27. }
  28. string Employee::chane_name(string n) {
  29. name = n;
  30. return name;
  31. }
  32. int main()
  33. {
  34. //方法1
  35. Employee emp[5]={
  36. Employee("Zhang San", "Haidian", "Beijing"),
  37. Employee("Li Si", "Xuanwu", "Beijing"),
  38. Employee("Wang Wu", "Nanfu", "Shanghai"),
  39. Employee("Zhu Ge", "Wuhou", "Chengdu"),
  40. Employee("Sun ying", "Zhifu", "Yantai")};
  41. //方法2
  42. /*Employee emp[5], * empOne = 0;
  43. empOne = new Employee("Zhang San", "Haidian", "Beijing", "100084");
  44. emp[0] = *empOne;
  45. delete empOne;
  46. empOne = new Employee("Li Si", "Xuanwu", "Beijing", "100031");
  47. emp[1] = *empOne;
  48. empOne = new Employee("Wang Wu", "Nanfu", "Shanghai", "012345");
  49. emp[2] = *empOne;
  50. empOne = new Employee("Zhu Ge", "Wuhou", "Chengdu", "543210");
  51. emp[3] = *empOne;
  52. empOne = new Employee("Sun ying", "Zhifu", "Yantai", "264000");
  53. emp[4] = *empOne;
  54. */
  55. for (int i = 0; i < 5; i++) {
  56. cout << "Number" << i << ':' << endl;
  57. emp[i].display();
  58. cout << endl;
  59. }
  60. getchar();
  61. // emp[0].display();
  62. return 0;
  63. }