对象指针

  • 对象在初始化后都会在内存空间中占有一定空间;
  • 既可以通过变量名也可以通过对象地址来访问对象;
  • 对象同时包含函数与数据;
  • 对象所占据的内存空间只是用于存放数据成员;

访问对象成员

  • 对象指针名 -> 成员名;
  • 类名 * 对象指针名;
  • 对象指针使用前需要将其初始化,初始化一个声明过的对象;
  • 通过对象指针可以访问对象的公有成员;

this指针

  • 隐含于每一个类的非静态成员函数的特殊指针;

  • 指向正在被成员函数操纵的对象;

  • this指针指出了成员函数当前所操作的数据所指的对象;

  • 当一个对象调用成员函数时,系统将该对象的地址传递给成员函数;

  • this指针是一个指针常量(所指地址不可改变);

指向对象的静态成员的指针

# include <iostream>
using namespace std;

class Point{
	public:
		Point(int x=0,int y=0):x(x),y(y){
		count++;
		}
		Point(const Point &p):x(p.x),y(p.y){
		count++;
		}
		~Point(){count --;}
		int getX() const {return x;}
		int getY() const {return y;}
		static int count;//静态数据成员声明
	private:
		int x,y;
};
int Point :: count = 0;

int main(){
	int *ptr = & Point :: count;//指向静态成员的 int型指针
	Point a(4,5);
	cout << a.getX() << endl;
	cout << *ptr << endl;//通过指针访问静态成员
	return 0;
} 

指向对象中静态函数的指针

# include <iostream>
using namespace std;

class Point{
	public:
		Point(int x=0,int y=0):x(x),y(y){
		count++;
		}
		Point(const Point &p):x(p.x),y(p.y){
		count++;
		}
		~Point(){count --;}
		int getX() const {return x;}
		int getY() const {return y;}
		static void showcount(){
		cout << count << endl;
		}
	private:
		int x,y;
		static int count;//静态数据成员声明
};
int Point :: count = 0;

int main(){
	
	void (* fptr)() = Point :: showcount;//指向对象静态函数的指针
	Point a(4,5);
	cout << a.getX() << endl;
	cout << fptr() << endl;//通过指针访问静态函数
	return 0;
} 在这里插入代码片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值