1.对象数组的每一个元素都是同类的对象
class Student
{
public:
Student(int score)//只有一个参数时
:_score(score){}
private:
int _score;
};
int main()
{
Student stu1[3] = { 60, 70, 90 };//三个实参分别传给数组的三个构造函数
return 0;
}
2.当数据成员中含有默认参数时
Student(int = 100, int = 80, int = 90);//含有默认参数时
Student stu2[3] = { 60, 70, 80 };//这三个实参分别作为三个元素的第一个实参
Student stu3 = { 20, 30, 40, 50 };//错误,实参个数不能超过对象元素个数
3.对象数组的使用方法
class Box
{
public:
Box(int h, int w, int len)
:height(h), width(w), length(len){}
int volume();
private:
int height;
int width;
int length;
};
int Box::volume()
{
return (height * width *length);
}
int main()
{
Box a[3] = {
Box(10, 12, 15),
Box(15, 18, 20),
Box(16, 20, 26)
};
cout << "volume of a[0] is " << a[0].volume() << endl;
cout << "volume of a[1] is " << a[1].volume() << endl;
cout << "volume of a[2] is " << a[2].volume() << endl;
system("pause\n");
return 0;
}
4,对象指针
对象空间的起始地址就是对象的指针
class Time
{
public:
int hour;
int minute;
int sec;
void get_time();
};
int main()
{
Time *pt;
Time t1;
pt = &t1;//pt就是指向Time类对象的指针变量
(*pt).hour;//pt所指向对象中的hour成员
pt->hour;
}
5,指向对象成员的指针
(1.)指向对象数据成员的指针
int *p;
p = &t1.hour;
cout << *p << endl;//输出t.hour的值
(2)指向对象成员函数的指针
void(Time::*p2)();//定义p2为指向Time类公用成员的指针变量
p2 = &Time::get_time;
6,有关对象指针的使用方法
class Time
{
public:
Time(int h, int m, int s)
:hour(h), minute(m), sec(s){}
void get_time();
int hour;
int minute;
int sec;
};
void Time::get_time()
{
cout << hour << ":" << minute << ":" << sec << endl;
}
int main()
{
Time t1(10, 13, 56);//定义Time类对象t1并初始化
int *p1 = &t1.hour;//定义指向整型数据的指针变量p1,并使p1指向t1.hour
cout << *p1 << endl;//10
t1.get_time();//调用对象t1的成员函数get_time 10:13:56
Time *p2 = &t1;//定义指向Time类对象的指针变量p2,并使p2指向t1
p2->get_time();//调用p2所指向对象的get_tiime函数 10:13:56
void(Time::*p3)();//定义指向Time类公用函数的指针变量p3
p3 = &Time::get_time;//使p3指向Time类公用成员函数get_time
(t1.*p3)();//调用t1对象中p3所指的成员函数(即get_time) 10:13:56
system("pause\n");
return 0;
}