this指針

#include <iostream>
using namespace std;

class A
{
public:
    int getnum(){ return i; }
    void setnum(int x){ i = x; cout << "this指針保存的內存地址爲:" << this << endl; }
    //void setnum(int x){this-> i = x; cout << "this指針保存的內存地址爲:" << this << endl; }
private:
    int i;
};

int main()
{
    A a;
    a.setnum(9);
    cout << "對象a的地址爲:" << &a << endl;
    cout << "對象a所的值爲:" << a.getnum() << endl;
    cout << 類的大小=<<sizeof(a)endl;
    A b;
    b.setnum(999);
    cout << "對象b的地址爲:" << &b << endl;
    cout << "對象b的值爲:" << b.getnum() << endl;
    cout << 類的大小=<<sizeof(b)endl;
    return 0;
}

這裏寫圖片描述

這裏寫圖片描述

從圖中對比可以看出

1.this指針所存放的類容和類對象地址是一樣的,所以this指針指向類對象。

2.類的大小不受this指針的影響,說明this指針不是類對象本身的一部分。
this指針是一個隱式參數但是可以顯示錶示

我們在原函數中添加一個test函數

void test()
{
    cout << "this的內容爲" << this << endl;
}

這裏寫圖片描述

從中我們可以得知,

3.this指針的作用域就在類的成員函數內部,

4.this指針只能在非靜態成員函數中才能使用,

``` 
 class A
{
public:
    int getnum(){ return i; }
    void setnum(int x)
    {
        this->i = x; cout << "this指針保存的內存地址爲:" << this << endl; int a = this;   }
private:
    int i;
};

結果如圖
這裏寫圖片描述
由圖可以得知

5.this指針的類型爲 類類型*const,

#include<iostream>
using namespace std;
class student
{
public:
void SetStuInfo(...);
private:
char _name[4];
char _gender[2];
int _number;
};
int main()
{
student s1;
s1.SetStuInfo("張三", "男", 20);
system("pause");
return 0;
}

這裏寫圖片描述
函數名稱修飾之後得到 ?SetStuInfo@student@AAXZZ

__thiscall調用約定:
1. 參數壓入堆棧從右往左。
2. this指針([s1]表示s1的地址)通過寄存器ecx傳遞
3. __thiscall只能夠用在類的成員函數上
4. 如果參數個數確定,this指針通過ecx傳遞給被調用者;如
果參數不確定(_cdecl),this指針在所有參數被壓入棧堆

#include<iostream>
using namespace std;
class student
{

public:
    void test1()
    {
        cout << this << endl;
    }
private:
    char _name[4];
    char _gender[2];
    int _number;
};
void test2()
{
    student* s1 = NULL;
    s1->test1();
}
int main()
{
    test2();
    system("pause");
    return 0;
}

這裏寫圖片描述
這說明了,this是能爲空的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章