this 关键字

this指针:

在C++中,每个对象都能通过 this 指针来访问自己的地址。this 指针是所有非静态成员函数的隐含参数。

1 . 每个成员函数内部(包括构造和析构)都有一个this指针;this指针指向被调用的成员函数所属的对象,即可通过this关键字访问当前对象的成员

访问成员变量
this->成员名;
访问成员函数
this->函数名();
	public:
        void InitScores();  //初始化学生成绩数组,默认分配1个元素空间
        void AddScore(float);   //向scores数组中添加一个分数
    private:
        int scoreCount; //学生成绩的个数
        float* scores;//学生的分数数组
void Student::InitScores()//初始化
{
    this->scores = new float[1];
    this->scoreCount = 1;
}
void Student::AddScore(float score)
{
    this->scores[this->scoreCount - 1] = score;
    //1.创建一个新数组,分配scoreCount + 1个空间
    //2.复制原数组的内容到新数组中
    //3.scoreCount++
    //4.scores指向新数组
    float* newScores = new float[scoreCount + 1];
    float* oldScores = scores;
    memcpy(newScores, scores, sizeof(float) * scoreCount);
    scoreCount++;
    scores = newScores;
    delete oldScores;
}

注:

  1. this指针的类型为类类型*const(类名 *const),为右值
  2. this指针本身不占用大小,他并不是对象的一部分,因此不会影响sizeof的结果
  3. this的作用域在类成员函数的内部
  4. this指针是类成员函数的第一个默认隐含参数,编译器自动维护传递,类编写者不能显示传递
  5. 只有在类的非静态成员函数中才可以使用this指针,其它任何函数都不可以
  6. 友元函数没有 this 指针,因为友元不是类的成员,只有成员函数才有 this 指针。
void MyShow(const Student* this){//C的写法:this在C++是函数的隐含第一个参数!
    this->AddScore()
}

2 . 在类的非静态成员函数中返回对象本身,可使用return *this

class Student{
public:
	Student& addScore(int score);
}

Student& Student::addScore(int score){
	this->score = this->score + score;
	return *this;
}

3.当形参和成员变量同名时,可用this指针区分

class Person {
public:
	Person(int age) {
		//this指针指向的是被调用的成员函数所属的对象
		this->age = age;
	}
	Person& PersoAddage(Person& p) {
		this->age += p.age;
		return *this;
	}
	int age;
};
int main(){
	Person p1(18);
	cout << p1.age << endl;
	Person p2(10);
	Person p3(10);
	//链式编程思想
	p3.PersoAddage(p2).PersoAddage(p2).PersoAddage(p2);
	cout << "p3的年龄为: " << p3.age << endl;
}

空指针访问成员函数

c++中空指针可以调用成员函数,但是要注意有没有用到this指针

class Person {
public:
	void showClassName() {
		cout << "this is showClassName" << endl;
	}
	void showPersonAge() {
		if (this == NULL) return;
		cout << m_age << endl;//传入的指针为空,报错
	}
	int m_age;
};
int main()
{
	Person* p = NULL;
	p->showClassName();
	p->showPersonAge();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值