对象数组的定义与访问
- 定义对象数组
类名 数组名[元素个数];
- 访问对象数组元素
对象数组初始化
- 数组中每一个元素对象被创建时,系统都会调用类构造函数初始化该对象。
- 通过初始化列表赋值。
例:Point a[2]={Point(1,2),Point(3,4)};
- 如果没有为数组元素指定显式初始值,数组元素便使用默认值初始化(调用默认构造函数)。
- 声明一个数组对象,有两种方法
方法1:
Employee emp[5]={
Employee("Zhang San", "Haidian", "Beijing"),
Employee("Li Si", "Xuanwu", "Beijing"),
Employee("Wang Wu", "Nanfu", "Shanghai"),
Employee("Zhu Ge", "Wuhou", "Chengdu"),
Employee("Sun ying", "Zhifu", "Yantai")};
方法2(动态申请内存,类似C#和Java那种写法)
Employee *emp1st = new Employee("Li Si", "Xuanwu", "Beijing");//定义一个指针变量emp1st
emp[0] = *emp1st;//指针所指的对象返回给数组
delete emp1st;//释放内存
数组元素所属类的构造函数
- 元素所属的类不声明构造函数,则采用默认构造函数。
- 各元素对象的初值要求为相同的值时,可以声明具有默认形参值的构造函数。
- 各元素对象的初值要求为不同的值时,需要声明带形参的构造函数。
- 当数组中每一个对象被删除时,系统都要调用一次析构函数。
实例代码
#include <iostream>
#include <string>
using namespace std;
int Client::ClientNum = 0;
char Client::ServerName = 'a';
class Employee {
private:
string name;
string streeName;
string city;
public:
Employee(string n, string s, string c) {
name = n;
streeName = s;
city = c;
};
Employee(){
name ="";
streeName ="";
city ="";
};
void display();
string chane_name(string n);
};
void Employee::display(){
cout << name << streeName << city<<endl;
}
string Employee::chane_name(string n) {
name = n;
return name;
}
int main()
{
//方法1
Employee emp[5]={
Employee("Zhang San", "Haidian", "Beijing"),
Employee("Li Si", "Xuanwu", "Beijing"),
Employee("Wang Wu", "Nanfu", "Shanghai"),
Employee("Zhu Ge", "Wuhou", "Chengdu"),
Employee("Sun ying", "Zhifu", "Yantai")};
//方法2
/*Employee emp[5], * empOne = 0;
empOne = new Employee("Zhang San", "Haidian", "Beijing", "100084");
emp[0] = *empOne;
delete empOne;
empOne = new Employee("Li Si", "Xuanwu", "Beijing", "100031");
emp[1] = *empOne;
empOne = new Employee("Wang Wu", "Nanfu", "Shanghai", "012345");
emp[2] = *empOne;
empOne = new Employee("Zhu Ge", "Wuhou", "Chengdu", "543210");
emp[3] = *empOne;
empOne = new Employee("Sun ying", "Zhifu", "Yantai", "264000");
emp[4] = *empOne;
*/
for (int i = 0; i < 5; i++) {
cout << "Number" << i << ':' << endl;
emp[i].display();
cout << endl;
}
getchar();
// emp[0].display();
return 0;
}