对象数组+对象指针+指向对象的指针

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;
}
  • 7
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值