C++(this指针)

文章目录

this指针

this 是 C++ 中的一个关键字,也是一个 const 指针,它指向当前对象,通过它可以访问当前对象的所有成员。所谓当前对象,是指正在使用的对象。例如对于stu.show();,stu 就是当前对象,this 就指向 stu。
注意,this 是一个指针,要用->来访问成员变量或成员函数。

#include <iostream>
using namespace std;

class Student{
	public:
	    void setname(string name);
	    void setage(int age);
	    void setscore(float score);
	    void show();
	private:
	    string name;
	    int age;
	    float score;
};

void Student::setname(string name){
    this->name = name;
}
void Student::setage(int age){
    this->age = age;
}
void Student::setscore(float score){
    this->score = score;
}
void Student::show(){
    cout<<this->name<<"的年龄是"<<this->age<<",成绩是"<<this->score<<endl;
}

int main(){
    Student *pstu = new Student;
    pstu -> setname("李华");
    pstu -> setage(16);
    pstu -> setscore(96.5);
    pstu -> show();
	delete pstu;
    return 0;
}

输出结果:
在这里插入图片描述

this 虽然用在类的内部,但是只有在对象被创建以后才会给 this 赋值,并且这个赋值的过程是编译器自动完成的,不需要用户干预,用户也不能显式地给 this 赋值。本例中,this 的值和 pstu 的值是相同的。

#include <iostream>
using namespace std;

class Student{
public:
	void printThis();
private:
    string name;
    int age;
    float score;
};

void Student::printThis()
{
	cout<<"this:"<<" "<<this<<endl;

}
int main(){
	Student *stu1 = new Student;
	stu1->printThis();
	cout<<"stu1:"<<" "<<stu1<<endl;
    
	Student *stu2 = new Student;
	stu2->printThis();
	cout<<"stu2:"<<" "<<stu2<<endl;
	
	delete stu1,stu2;//释放
	return 0;
}

输出结果:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秃秃秃秃哇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值