一、对象数组
1、概念
对象数组本质上就是:数组中每一个元素都是同一个类的对象。
Box aa[3]={
Box(1, 1, 1),
Box(2, 2, 2),
Box(3, 3, 3)
};
2、练习代码
#include <iostream>
using namespace std;
class Box
{
public:
Box(int h=10, int w=12, int len=15): 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 aa[3]={
Box(1, 1, 1),
Box(2, 2, 2),
Box(3, 3, 3)
};
cout << "对象盒子1的体积为:" << aa[0].Volume() << endl;
cout << "对象盒子2的体积为:" << aa[1].Volume() << endl;
cout << "对象盒子3的体积为:" << aa[2].Volume() << endl;
}
二、对象指针
1、概念
对象指针本质上就是:指向对象成员的指针。
这个对象存储空间的起始地址就是对象的指针,可以定义一个指针变量,用来存放对象的地址,这就是指向对象的指针变量。
2、对象指针的用法规则
- 定义指向对象的指针形式:
类名 *对象指针名;
定义指向数据成员的指针:对象指针名*成员名;
Time *pt;
Time t1;
pt= &t1;
void (*p)();
3、对象指针访问成员数据和成员函数
(*pt).hour
pt->get_time()
(*pt).get_time()
4、对象指针练习代码
#include <iostream>
using namespace std;
class Time
{
public:
Time(int, int, int);
int hour;
int minute;
int sec;
void show_time();
};
Time::Time(int h, int m, int s)
{
hour= h;
minute= m;
sec= s;
}
void Time::show_time()
{
cout << hour << ":" << minute << ":" << sec << endl;
}
int main()
{
Time t1(12, 23, 34);
int *p1= &t1.hour;
cout << "指针p1指向地址中存有:" << *p1 << endl;
t1.show_time();
Time *p2= &t1;
p2->show_time();
void(Time::*p3)();
p3= &Time::show_time;
(t1.*p3)();
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)