this指针

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

源程序

main.cpp

#include <iostream>
#include <string>
#include "Student.h"

using namespace std;
/**this 是 C++ 中的一个关键字,也是一个 const 指针,它指向当前对象,通过它可以访问当前对象的所有成员。
所谓当前对象,是指正在使用的对象。例如对于stu.show();,stu 就是当前对象,this 就指向 stu。
this 虽然用在类的内部,但是只有在对象被创建以后才会给 this 赋值,
并且这个赋值的过程是编译器自动完成的,不需要用户干预,用户也不能显式地给 this 赋值。
*/

int main()
{
    Student* ptr_student = new Student;
    ptr_student->set_name("改改笨笨");
    ptr_student->set_age(28);
    ptr_student->set_score(99.8);
    ptr_student->show();
    /**本例中,this 的值和 ptr_student 的值是相同的。
    我们不妨来证明一下,给 Student 类添加一个成员函数printThis(),专门用来输出 this 的值
    */
    cout << "ptr_student的值是:" << ptr_student << endl;
    cout << "this的值是:" ;
    ptr_student->printThis();
    cout << "************************************\n";
    Student* ptr_student2 = new Student;
    cout << "ptr_student2的值是:" << ptr_student << endl;
    cout << "this的值是:" ;
    ptr_student2->printThis();
    cout << "************************************\n";
    delete ptr_student;
    delete ptr_student2;
    return 0;
}

include\Student.h

#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <string>

using namespace std;

class Student
{
    public:
        Student();
        virtual ~Student();
        void set_name(string);
        void set_age(int);
        void set_score(float);
        void show();
        void printThis();

    protected:

    private:
        string name;
        int age;
        float score;
};

#endif // STUDENT_H

src\Student.cpp

#include "Student.h"

Student::Student()
{
    //ctor
    cout << "我是默认构造函数" << endl;
}

Student::~Student()
{
    //dtor
    cout << "空间释放了" << endl;
}

void Student::set_name(string Name)
{
    this->name = Name;
}
void Student::set_age(int Age)
{
    this->age = Age;
}
void Student::set_score(float Score)
{
    this->score = Score;
}
void Student::show()
{
    cout << this->name << "的年龄是:" << this->age <<", 成绩是:" << this->score << "分" << endl;
}
void Student::printThis()//用来输出 this 的值
{
    cout << this << endl;
}

运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值