04-03 对象指针

对象指针

【Example 1】

指向对象的指针

#include <iostream>
using namespace std;
class exe
{
    private:
        int x;
    public:
        void set_x(int x) { this->x = x; }
        void show() { cout << x << endl; }
};
int main()
{
    exe ob, *p;
    ob.set_x(1);
    cout << "ob.show()=";
    ob.show();

    cout << "p->show()=";
    p->show();

    p = &ob;    // 将对象ob的地址值赋给对象指针p
    cout << "p->show()=";
    p->show();
    return 0;
}
/*
ob.show()=1
p->show()=1528349827
p->show()=1
*/

【Examplc 2】

对象指针访问对象数组

#include <iostream>
using namespace std;
class exe
{
    private:
        int x;
    public:
        void set_x(int x) { this->x = x; }
        void show() { cout << x << endl; }
};
int main()
{
    exe ob[3];
    ob[0].set_x(11);
    ob[1].set_x(22);
    ob[2].set_x(33);

    exe *p = ob;        // 将对象数组ob的首地址赋给对象指针
    cout << "p->show()=";
    p->show();

    cout << "(++p)->show()=";
    (++p)->show();      // 一般,当指针加1时,指针指向该数组下一个对象

    cout << "ptr=&ob[2]" << endl;
    exe *ptr = &ob[2];  // 直接取出数组中某个元素的地址赋给指针
    cout << "ptr->show()=";
    ptr->show();

    return 0;
}
/*
p->show()=11
(++p)->show()=22
ptr=&ob[2]
ptr->show()=33
*/

【Example 3】

指向类的成员的指针

  • 指针直接指向对象的成员,进而可以通过指针访问对象的成员
  • 只能访问公有数据成员和成员函数
  • 使用时:先声明,再赋值,然后访问

指向数据成员的指针

#include <iostream>
using namespace std;
class A{
    public:
        int x;
        A(int x) { this->x = x; }
};
int main()
{
    A ob(205);
    A *p = &ob;

    int A::*ptr;    // 声明
    ptr = &A::x;    // 赋值

    cout << ob.*ptr << endl;    // 使用
    cout << p->*ptr << endl;    // 使用
    cout << ob.x << endl;

    return 0;
}
/*
205
205
205
*/

指向对象成员函数的指针

#include <iostream>
using namespace std;
class Coord
{
    private:
        int x, y;
    public:
        Coord(int a = 0, int b = 0) { x = a, y = b; }
        int get_x() { return x; }
        int get_y() { return y; }
};
int main()
{
    Coord ob(17, 54);
    Coord *p = &ob;

    int (Coord::*p_get_x)();    // 声明
    p_get_x = &Coord::get_x;    // 赋值

    cout << ob.get_x() << endl;
    cout << p->get_x() << endl;
    cout << (ob.*p_get_x)() << endl;    // 使用
    cout << (p->*p_get_x)() << endl;    // 使用

    return 0;
}
/*
17
17
17
17
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值