- 对象在初始化后都会在内存空间中占有一定空间;
- 既可以通过变量名也可以通过对象地址来访问对象;
- 对象同时包含函数与数据;
- 对象所占据的内存空间只是用于存放数据成员;
访问对象成员
- 对象指针名 -> 成员名;
- 类名 * 对象指针名;
- 对象指针使用前需要将其初始化,初始化一个声明过的对象;
- 通过对象指针可以访问对象的公有成员;
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;
} 在这里插入代码片