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对象的地址,并且应用指针的形式返回当前的对象。

猜你喜欢

转载自blog.csdn.net/xiadeliang1111/article/details/82957960