C++ this指针详解(精辟)

link

this 是 C++ 中的一个关键字,也是一个 const 指针,它指向当前对象,通过它可以访问当前对象的所有成员。所谓当前对象,是指正在使用的对象。例如对于stu.show();,stu 就是当前对象,this 就指向 stu。
下面是使用 this 的一个完整示例:
#include <iostream>
using namespace std;

class Student{

public:
    void setname(char *name );
    void setage( int age );
    void setmoney(float score );
    void show();
private:
    char * name;
    int age ;
    float score;

};


void Student::setname(char *name )
{
    this->name =name;
}

void Student::setage(int age )
{
    this->age =age;
}

void Student::setmoney(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( 33);
    pstu->setmoney(1);

    pstu ->show();
    return 0 ;
}

posted @ 2022-08-19 22:48  luoganttcc  阅读(17)  评论(0)    收藏  举报