04-01 this指针

自引用指针this

this指针:

成员函数隐藏定义的常量指针

  • 类型:类的类型
  • 指向:当前对象
  • 通过它可以访问当前对象的所有成员
  • 在通常情况下,this指针在系统中是隐含地存在的。也可以将其显式地表示出来。
  • const指针,不能在程序中修改或赋值
  • 作用域在对象内部,可通过this访问private,public,protected属性成员
  • 对象被创建后才给this赋值,由编译器自动完成

调用:

调用成员函数时,它被初始化为被调函数所在类的对象的地址。也就是自动地将对象的指针传给它。

不同的对象调用同一个成员函数时,编译器将根据成员函数的this指针所指向的对象来确定应该引用哪一个对象的数据成员。

【Example 1】显式表示this指针

#include <iostream>
using namespace std;

class A
{
    private:
        int x;
    public:
        A(int x1) { x = x1; }
        void disp()
        {
            cout << "this=" << this << "\tx=" << this->x << endl;
        }
};
int main()
{
    A a(1), b(2), c(3);
    a.disp();
    b.disp();
    c.disp();
    return 0;
}

/*
output:
this=0x61feec   x=1
this=0x61fee8   x=2
this=0x61fee4   x=3
*/

【Example 2】this和*this的用法

#include <stdlib.h>

#include <iostream>
using namespace std;

class Sample
{
    private:
        int x, y;
    public:
        Sample(int i=0,int j=0)
        {
            x = i;
            y = j;
            cout << "constructing..." << endl;
        }
        void copy(Sample &s){
            if(this==&s)    // 若拷贝其本身,则直接返回
                return;
            *this = s;      // 深拷贝?
                            // *this表示当前对象本身
        }
        void print(){
            cout << x << "," << y << endl;
        }
        void set_x(int x) { this->x = x; }
        ~Sample()
        {
            cout << "destructing..." << endl;
        }
};
int main()
{
    Sample p1(1, 1), p2(5, 6);
    p1.print();
    p2.print();

    p1.copy(p2);
    p1.print();

    p2.set_x(2);
    p2.print();
    p1.print();
    return 0;
}
/*
output:
constructing...
constructing...
1,1
5,6
5,6
2,6
5,6
destructing...
destructing...
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值