日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > c/c++ >内容正文

c/c++

C++——this指针

發(fā)布時(shí)間:2025/4/16 c/c++ 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++——this指针 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

this指針

在 C++ 中,每一個(gè)對(duì)象都能通過(guò)?this?指針來(lái)訪問(wèn)自己的地址。this?指針是所有成員函數(shù)的隱含參數(shù)。因此,在成員函數(shù)內(nèi)部,它可以用來(lái)指向調(diào)用對(duì)象。

友元函數(shù)沒(méi)有?this?指針,因?yàn)橛言皇穷?lèi)的成員。只有成員函數(shù)才有?this?指針。

#include <iostream>using namespace std;class Box {public:// 構(gòu)造函數(shù)定義Box(double l=2.0, double b=2.0, double h=2.0){cout <<"Constructor called." << endl;length = l;breadth = b;height = h;cout << this->length << endl ;cout << this->breadth << endl ;cout << this->height << endl ;}double Volume(){return length * breadth * height;}int compare(Box box){return this->Volume() > box.Volume();}private:double length; // Length of a boxdouble breadth; // Breadth of a boxdouble height; // Height of a box };int main(void) {Box Box1(3.3, 1.2, 1.5); // Declare box1Box Box2(8.5, 6.0, 2.0); // Declare box2if(Box1.compare(Box2)){cout << "Box2 is smaller than Box1" <<endl;}else{cout << "Box2 is equal to or larger than Box1" <<endl;}return 0; }/* 輸出結(jié)果是 Constructor called. 3.3 1.2 1.5 Constructor called. 8.5 6 2 Box2 is equal to or larger than Box1 */

指向類(lèi)的指針

一個(gè)指向 C++ 類(lèi)的指針與指向結(jié)構(gòu)的指針類(lèi)似,訪問(wèn)指向類(lèi)的指針的成員,需要使用成員訪問(wèn)運(yùn)算符?->,就像訪問(wèn)指向結(jié)構(gòu)的指針一樣。與所有的指針一樣,必須在使用指針之前,對(duì)指針進(jìn)行初始化。

#include <iostream>using namespace std;class Box {public:// 構(gòu)造函數(shù)定義Box(double l=2.0, double b=2.0, double h=2.0){cout <<"Constructor called." << endl;length = l;breadth = b;height = h;cout << this->length << endl ;cout << this->breadth << endl ;cout << this->height << endl ;}double Volume(){return length * breadth * height;}int compare(Box box){return this->Volume() > box.Volume();}private:double length; // Length of a boxdouble breadth; // Breadth of a boxdouble height; // Height of a box };int main(void) {Box Box1(3.3, 1.2, 1.5); // Declare box1Box Box2(8.5, 6.0, 2.0); // Declare box2Box *ptr ; // 創(chuàng)建一個(gè)指向類(lèi)的指針ptr = &Box1 ; // 保存Box1對(duì)象的地址cout << ptr->Volume() << endl; // 使用成員訪問(wèn)運(yùn)算符來(lái)訪問(wèn)成員ptr = &Box2 ;cout << ptr->Volume() << endl;return 0; }/* 輸出結(jié)果是 Constructor called. 3.3 1.2 1.5 Constructor called. 8.5 6 2 5.94 102 */

部分資料來(lái)源于菜鳥(niǎo)教程

《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專(zhuān)家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的C++——this指针的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。