C++ this指針

this指針的用途

1.this指向被調用成員函數所屬的對象

class stu {
public:
	int num;
	stu(int num) {
		this->num = num;//this指向被調用成員函數所屬的對象
	}
	void get() {
		cout << num << endl;
	}
};

int main(){

	stu s(100);
	s.get();//100
}

2.返回對象本身用 *this

注意若要返回對象本身,返回對象的類型須爲引用
因爲若不是引用,構造器默認的拷貝構造函數,將會把該類拷貝一份,而並非該類本身

class stu {
public:
	int num;
	stu(int num) {
		this->num = num;//this指向被調用成員函數所屬的對象
	}
	stu& set(stu s) {
		this->num += s.num;
		return *this;//返回本身
	}
	
};

int main(){

	stu s(100);
	s.set(s).set(s).set(s);
	cout << s.num;
	
}

空指針訪問成員函數

空指針也可以訪問成員函數

class stu {
public:
	int num=10;
	
	void set() {
		cout << "hellow  CSDN"<< endl;
	}

	void get() {
		cout << num << endl;//num想當是 this.num
	}
};

int main(){

	stu *s=NULL;
	s->set();
}

在這裏插入圖片描述
但是如果調用 get()函數

int main(){

	stu *s=NULL;
	s->get();
}

會報錯在這裏插入圖片描述
爲什麼呢?
num其實是 this.num,問我們將它指向了空指針,所以讀取時會異常

成員變量和成員函數分開儲存

只有非靜態成員變量才屬於類的對象上

class Stu {

};
int main(){
	Stu p;
cout << sizeof(p);//1
}

空對象佔用內存爲1,編譯器會爲每個空對象分配1個字節的空間

class Stu {
	int p;//非靜態成員變量
};
int main(){
	Stu p;
cout << sizeof(p);//4
}

當只有非靜態成員變量時佔內存大小爲 4;

class Stu {
	int p;//非靜態成員變量
	static int f;//靜態成員變量
	void q() {};//靜態成員函數
	static void w() {}; //非靜態成員函數
};
int main(){
	Stu p;
cout << sizeof(p);//4
}

此時佔內存大小仍爲4,所以可得 只有非靜態成員變量才屬於類的對象上

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