4.3 C++对象模型和this指针
4.3.1 成员变量和成员函数分开存储
在C++
中,类内的成员变量和成员函数分开存储
只有非静态成员变量才属于类的对象上
示例
#include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class point1{
int x; //非静态成员变量占对象空间
};
class point2{
int x; //非静态成员变量占对象空间
static int y; //静态成员变量不占对象空间
void fx(){ //函数也不占对象空间,所有函数共享一个函数实例
}
static void fy(){ //静态成员函数也不占对象空间
}
};
int main(){
cout<<sizeof(point1)<<endl;
cout<<sizeof(point2)<<endl;
}
注意: C++
编译器会给空对象分配一个字节,用于区分其存储空间
4.3.2 this指针概念
C++
中成员变量和成员函数是分开存储的,每一个非静态成员函数只会诞生一份函数实例,也就是说多个同类型的对象会共用一块代码
那么问题是:这一块代码是如何区分那个对象调用自己的呢?
C++
通过提供特殊的对象指针,this指针,解决上述问题。this指针指向被调用的成员函数所属的对象
概念
-
this指针是隐含每一个非静态成员函数内的一种指针
-
this指针不需要定义,直接使用即可
用途:
-
当形参和成员变量同名时,可用this指针来区分
-
在类的非静态成员函数中返回对象本身,可使用return *this
示例
#include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class point{
public:
int x,y;
//1、当形参和成员变量同名时,可用this指针来区分
point(int x,int y){
this->x=x;
this->y=y;
}
point& add(point p){
this->x+=p.x;
this->y+=p.y;
//返回对象本身
return *this;
}
};
void test01(){
point p1(1,2);
cout<<p1.x<<" "<<p1.y<<endl;
}
void test02(){
point p2(1,1);
point p3(0,0);
p3.add(p2).add(p2).add(p2);
cout<<p2.x<<" "<<p2.y<<endl;
}
int main(){
test01();
test02();
return 0;
}
4.3.3 空指针访问成员函数
C++
中空指针也是可以调用成员函数的,但是也要注意有没有用到this指针
如果用到this指针,需要加以判断保证代码的健壮性
示例:
#include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class point{
public:
int x,y;
point(int a,int b):x(a),y(b) {}
void show_1(){
cout<<"YES"<<endl;
}
void show_2(){
cout<<x<<" "<<y<<endl; //默认使用了this指针
// cout<<this->x<<this->y<<endl; //与上一行等价
}
};
int main(){
point *p1=NULL;
p1->show_1(); //空指针,可以调用成员函数
p1->show_2(); //但是如果成员函数中用到了this指针,就不可以了
return 0;
}
4.3.4 const修饰成员函数
常函数:
-
成员函数后加
const
后我们称为这个函数为常函数 -
常函数内不可以修改成员属性
-
成员属性声明时加关键字
mutable
后,在常函数中依然可以修改
常对象:
-
声明对象前加
const
称该对象为常对象 -
常对象只能调用常函数
示例:
#include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class point{
public:
int x;
mutable int y; //可修改 可变的
point(){
x=10;
y=10;
}
//this指针的本质是一个指针常量,指针的指向不可修改
//如果想让指针指向的值也不可以修改,需要声明常函数
void show_1() const{
//const Type* const pointer;
//this = NULL; //不能修改指针的指向 Person* const this;
//this->mA = 100; //但是this指针指向的对象的数据是可以修改的
//const修饰成员函数,表示指针指向的内存空间的数据不能修改,除了mutable修饰的变量
this->y=20;
cout<<x<<" "<<y<<endl;
}
void show_2(){
cout<<x<<" "<<y<<endl;
}
// void show_no() const{
// this->x=20;
// }
};
int main(){
point p1;
p1.show_1(); //非常对象可以调用const函数
const point p2; //常量对象
// p2.x=20; //常对象不能修改成员变量的值,但是可以访问
p2.y=100; //但是常对象可以修改mutable修饰成员变量
//常对象访问成员函数
p2.show_1();
// p2.show_2(); //常对象只能调用const函数
return 0;
}