对象数组,对象指针

数组不仅可以由简单的变量组成,还可以由对象组成

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Achou.Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值