对象数组与对象指针
1. 对象数组
所谓对象数组是指每一数组元素都是对象的数组, 也就是说,若一个类有若干个对象,则把这一系列的对象用一个数组来存放。
对象数组的元素是对象, 不仅具有数据成员,而且还有函数成员
定义一个一维数组的格式如下:
类名 数组名[下标表达式];
exam ob[4]; //定义了类exam的对象数组ob.
与基本数据类型的数组一样,在使用对象数组时也只能访问单个数组元素,也就是一个对象,通过这个对象,也可以访问到它的公有成员
使用的一般形式是:
数组名[下标].成员名
例3.4 对象数组的应用
#include<iostream.h>
class exam{
public:
void set_x(int n){ x=n; }
int get_x(){ return x; }
private:
int x;
};
main()
{
exam ob[4];
int i;
for (i=0;i<4;i++)
ob[i].set_x(i);
for (i=0;i<4;i++)
cout<<ob[i].get_x()<<′ ′;
cout<<endl;
return 0;
}
0 1 2 3
如果需要建立某个类的对象数组,在设计类的构造函数时就要充分考虑到数组元素初始化的需要;
- 当各个元素的初值要求为相同的值时,应该在类中定义出不带参数的构造函数或带缺省参数值的构造函数;
- 当各元素对象的初值要求为不同的值时需要定义带形参(无缺省值)的构造函数。
- 定义对象数组时,可通过初始化表进行赋值。定义对象数组时,可通过初始化表进行赋值
【例3.5】 通过初始化表给对象数组赋值
#include<iostream.h>
class exam{
public:
exam()
{ x=123;}
exam(int n)
{ x=n;}
int get_x()
{ return x; }
private:
int x;
};
main()
{
exam ob1[4]={11,22,33,44};
exam ob2[4]={55,66};
exam ob3[4]={exam(11),exam(22),exam(33),exam(44)};
exam ob4[4]={exam(55),exam(66)};
ob4[2]=exam(77);
ob4[3]=exam(88);
int i;
for (i=0;i<4;i++)
cout<<ob1[i].get_x()<<' ';
cout<<endl;
for (i=0;i<4;i++)
cout<<ob2[i].get_x()<<' ';
cout<<endl;
for (i=0;i<4;i++)
cout<<ob3[i].get_x()<<' ';
cout<<endl;
for (i=0;i<4;i++)
cout<<ob4[i].get_x()<<' ';
cout<<endl;
return 0;
}
11 22 33 44
55 66 123 123
11 22 33 44
55 66 77 88
【例3.6】 本例说明当构造函数具有一个以上的参数时,如何对二维数组对象进行初始化
#include <iostream.h>
class example{
public:
example(int n, int m)
{
x = n;
y = m;
}
~example()
{ cout<<"Destructor called.\n"; }
int get_x()
{ return x;}
int get_y()
{ return y;}
private:
int x, y;
};
main()
{
example op[3][2]={
example(1,2),example(3,4),
example(5,6),example(7,8),
example(9,10),example(11,12) };
int i;
for (i=0;i<3;i++)
{
cout<<op[i][0].get_x()<<' ';
cout<<op[i][0].get_y()<<"\n";
cout<<op[i][1].get_x()<<' ';
cout<<op[i][1].get_y()<<"\n";
}
cout<<"\n";
return 0;
}
1 2
3 4
5 6
7 8
9 10
11 l2
Destructor called.
Destructor called.
Destructor called.
Destructor called.
Destructor called.
Destructor called.
2. 对象指针
每一个对象在初始化后都会在内存中占有一定的空间。因此,即可以通过对象名访问一个对象,也可以通过对象地址来访问一个对象。
对象指针就是用于存放对象地址的变量。声明对象指针的一般语法形式为:类名* 对象指针名;
(1)用指针访问单个对象成员
- 定义指针变量:
Date *p,date1;
- 初始化:指向一个已创建的对象
p=&date1;
访问:用“->”操作符,只能访问该对象的公有成员。
p->setdate(2007,10,18);
例3.7 对象指针的使用
#include<iostream.h>
class exe{
public:
void set_a(int a){ x=a; }
void show_a(){ cout<<x<<endl; }
private:
int x;
};
main()
{
exe ob,*p; // 声明类exe的对象ob和类exe的对象指针p
ob.set_a(2);
ob.show_a(); // 利用对象名访问对象的成员
p=&ob; // 将对象ob的地址赋给对象指针p
p->show_a(); // 利用对象指针访问对象的成员
return 0;
}
2
2
(2)用对象指针访问对象数组
对象指针不仅能访问单个对象,也能访问对象数组.
exe *p; //声明对象指针p
exe ob[2]; //声明对象数组ob[2]
p=ob; //将对象数组的首地址赋给对象指针
main()
{
exe ob[2],*p;
ob[0].set_a(10);
ob[1].set_a(20);
p=ob;
p->show_a();
p++;
p->show_a();
return 0;
}
结果:
10 20
一般而言,当指针加1或减1时,它总是指向其基本类型中相邻的一个元素,对象指针也是如此. 本例中指针对象p加1时,指向下一个数组对象元素.
【例3.8】 本例说明如何通过对象指针来访问对象数组,使程序以相反的顺序显示对象数组的内容
#include <iostream.h>
class example{
pu