1.this指针
1.1 this指针简介
this指针是类中成员函数的一种隐藏的指针,可以将其视为每个成员函数的形参,当对象调用成员函数的时候,会把对象的地址传给this指针,所以this指针会指向调用成员函数的对象。
1.2 this指针演示
#include<iostream>
using namespace std;
class person
{
public:
int age;
char sex;
person() :age(18), sex('b') {}
void display()
{
cout << age << " " << sex << endl;
//这里相当于输出this->age,this->sex
}
void thisdisplay()
{
cout << this<<endl;
}
person* getthis()
{
return this;
}
};
int main()
{
person p1;
p1.thisdisplay();
p1.display();//用成员函数输出
cout << p1.getthis()->age << " " << p1.getthis()->sex << endl;//用得到的this指针输出
return 0;
}
1.3 this指针的用处
下面是个人了解到的会用到this指针的地方。
如在前置自增运算符中会有return *this
可以使其连续自增
在拷贝赋值运算符中
2.const关键字
2.1 回顾C语言中的用法
int b = 10;
const int* a = &b;
b = 20;
cout << b;//b的值仍可以改变
*a = 30;//编译器报错,虽然b的值可改,但是不可以通过a指针来改变b
const在左边 a指针指向的数据不可通过指针a改变。(等下讲的会和这里有关)!!!
2.2 const成员函数
const成员函数的定义:在花括号前加上const。
void display () const
{
cout << age << " " << sex << endl;
}
被const修饰的成员函数只可以访问对象中的数据,但是不能对其进行修改操作
例如上图中的输出操作可以进行,但如果加上改变数据的语句就会报错
void display () const
{
age++;//此处报错
cout << age << " " << sex << endl;
}
原因分析:
本质上,const修饰成员函数是对成员函数的this指针进行const修饰,使得const成员函数不能通过this指针来修改对象中的数据(如刚才回顾const用法中的一样)类比一下上面写的const int*a=&b;const修饰成员函数相当于 const this=对象地址。
2.3 const对象
对对象进行const修饰的含义是限定此对象中的成员变量不可修改。
又因为编译器无法判断对象的非const成员函数是否会改变成员变量,所以禁止const对象调用任何非const的成员函数。而const成员函数一定不会改变成员变量,所以可以调用const成员函数。
还拿之前的代码举例:
#include<iostream>
using namespace std;
class person
{
public:
int age;
char sex;
person() :age(18), sex('b') {}
void display () const
{
cout << age << " " << sex << endl;
}
void thisdisplay()
{
cout << this<<endl;
}
person* getthis()
{
return this;
}
};
int main()
{
const person p1;
p1.thisdisplay();//错误,不可以调用非const成员函数
p1.display();//正确,可以调用加了const的成员函数
return 0;
2.4 const的主要用处和注意事项
const的主要作用是保护数据,防止程序运行过程中意外对不该改变的数据进行修改,在正确的地方使用const可以增强代码的安全性。
注意:const成员变量需要在构造函数的参数列表中进行初始化。
3.static关键字
3.1 static基本介绍
static修饰变量会改变变量的存放位置,静态变量将会被存处在堆区,static会改变变量的生命周期,但是不会改变作用域。
3.2 static成员变量
static成员变量需要在类外进行初始化,每个static成员变量是属于整个类的,而不是属于某个对象。在没有对象实例化之前,static成员变量就已经存在。
3.3 static成员函数
static函数同样不属于任何一个对象,为整个类所有。因为static函数不具有this指针,当用对象调用static函数的时候,无法对特定对象中非static成员变量进行操作,因此static成员函数只可以访问类中的static成员变量,无法访问非static成员变量。
#include<iostream>
using namespace std;
class person
{
public:
int age;
char sex;
static double weight;
static double getweight()
{
return weight;
}//正确 static成员函数调用static成员变量
static double ageget()
{
return age;
}//添加了这段代码程序便会报错
};
double person::weight=0;
int main()
{
person p1;
cout<<p1.getweight();
return 0;
}
4.static const同时修饰
static const和const static是相同的,修饰成员变量时代表静态的常量成员变量,在类外和类内都可以进行初始化。
#include<iostream>
using namespace std;
class person
{
public:
int age;
char sex;
static const int sc=0;
static const int kk;
};
int kk=0;
int main()
{
person p1;
cout<<p1.getweight();
cout<<kk;
return 0;
}