this指針,this為空,nullptr訪問成員函數


一、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();  //正確
}

五、this使用實例

C++重載運算符

其他

轉載:C++類中this的理解


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM