对象指针
【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
*/