数组不仅可以由简单的变量组成,还可以由对象组成
#include <iostream>
//#include "student.h"
#include <string>
//#include <cstring>
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 a[3]={ //定义一个对象数组
Box(10,12,15), //调用构造函数数组,Box,提供第一个元素的实参
Box(15,18,23), //提供第二个元素的实参
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;
return 0;
}
指针可以用来指向一般的变量,也可以指向对象。
指向对象的指针,在建立对象的过程中,编译系统会给对象分配同一个存储空间,对象空间的起始地址就是就是对象的指针。
对象有地址,存放对象初始地址的指针变量就是指向对象的指针变量。对象中的成员也有地址,存放对象成员地址的指针变量就是指向对象成员的指针变量。
#include <iostream>
//#include "student.h"
#include <string>
//#include <cstring>
using namespace std;
class Time{
public:
Time(int,int,int); //定义一个构造函数
int hour;
int minute;
int sec;
void gettime();
};
Time::Time(int h,int m,int s)
{
hour=h;
minute=m;
sec=s;
}
void Time::gettime() {
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; //输出p1所指向的对象
t1.gettime(); //调用t1的成员函数gettime
Time *p2=&t1; //定义一个指向Time类对象的指针p2,并使p2指向t1;
p2->gettime(); //调用p2所指向的对象的成员函数即t1的函数gettime;
void(Time::*p3)(); //声明一个指向Time类的公共函数的指针p3,
p3=&Time::gettime; ///使指针p3指向Time类的公共函数gettime
(t1.*p3)(); 调用对象中t1中p3所指向的成员函数(t1.gettime())
return 0;
}