一、this的定義
this指針是存在於類的成員函數中,指向被調用函數所在的類實例的地址。一個對象的this指針並不是對象本身的一部分,也就意味着並不會影響sizeof的結果。
二、this的作用
保存當前對象的地址,是一個常量指針,不允許改變this的值
三、為什么使用this指針
-
在類的非靜態成員函數中返回類對象本身的時候,直接使用 return *this;
-
當參數與成員變量名相同時,如this->n = n (不能寫成n = n)。
四、this指針為空(nullptr對象為什么可以調用函數)
this指針為空,即當前的對象為nullptr,如果編譯器報錯this為空,請檢查當前的對象是否空。
this指針為空即一個nullptr對象,不能調用含有非靜態成員的函數(只能調用不使用this指針的函數)。
對象調用非靜態成員函數時,編譯器會默認把this指針作為第一個參數!即void func(args) = void func(this,args)
點擊查看代碼
#include <iostream>
using namespace std;
class test
{
public:
static void f1() { cout << y << endl; }
void f2() { cout << y << endl; } // void f2(test* t){cout << y << endl;} 因為y是靜態的,所以不需要使用this指針
void f3() { cout << x << endl; } // 相當於 cout<< this->x <<endl;
void f4(int p) { cout << p << endl; }
void f5() { cout << 5 << endl; }
int f6() { return 6; }
//static void f7() { cout << x << endl; } //靜態函數不能調用非靜態成員變量
int x;
static int y;
};
int test::y = 1;
int main()
{
test* p = nullptr;
p->f1();
p->f2(); // p->f2(p); p在f2函數體內並不使用,所以正確
//p->f3(); //cout << nullptr->x << endl; 錯誤
p->f4(5);
p->f5();
p->f6();
getchar();
return 0;
}
點擊查看代碼
nullptr不能調用virtual函數,子類自己的函數只要不訪問非靜態成員仍然可以調用
#include <iostream>
class A
{
public:
virtual void Func()
{
std::cout << "a\n";
}
};
class B :
public A
{
public:
void FuncB()
{
std::cout << "b\n";
}
};
int main()
{
B* b = nullptr;
//b->Func(); // 拋出異常,因為b是nullptr沒有虛表
b->FuncB(); //正確
}