C++this指针初步介绍

参考:https://www.cnblogs.com/liushui-sky/p/5802981.html

C++中经常用到的this指针,指代这个类对象的本身。

比如String类,声明了一个对象String myString,myString里的this就是指向myString对象的指针,this就是这个类对象的地址。

 

this 的使用:一种情况是,在类的非静态成员函数中返回类对象本身的时候,直接使用return *this;另外一个情况就是当参数与成员变量名相同时,如this->n = n(不能写成n=n);

接下来用一段程序来看一下this指针:

#include <iostream>
#include <string.h>
using namespace std;

class String
{
public:
    String(const char *);
    String& operator=(const String &other);
    char *get_data(){return data;}
private:
    char *data;
};

String::String(const char *str)
{
    int length = strlen(str) + 1;
    data = new char[length];
    memset(data, 0, length);
    strcpy(data, str);
}
String &String::operator=(const String &other)
{
    cout<<"operator= function"<<endl;
    cout<<"other address:"<<&other<<endl;
    cout<<"this address:"<<this<<endl;
    if(this == &other)
    {
        return *this;
    }
    int length = strlen(other.data) + 1;
    delete[] data;
    data = new char[length];
    memset(data, 0, length);
    strcpy(data, other.data);
    return *this;
}
int main()
{
    String a("hello");
    String b("world");
    cout<<"a address:"<<&a<<endl;
    cout<<"b address:"<<&b<<endl;
    b = a;
}

结果:

[root@localhost workplace]# ./test
a address:0x7ffda90eb900
b address:0x7ffda90eb8f0
operator= function
other address:0x7ffda90eb900
this address:0x7ffda90eb8f0

可以看到,b对象的地址与运算符函数中的this地址是一样的,也就是说this指针保存了b对象的地址,并且应用指针的形式返回当前的对象。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值