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

歡迎訪問 生活随笔!

生活随笔

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

c/c++

C++基础之成员变量的秘密

發(fā)布時間:2024/5/14 c/c++ 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++基础之成员变量的秘密 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
#include <iostream> using namespace std;extern int gl; //我們聲明了一個全局變量gl,在哪里?不知道class A { public:void f();int i; //類里面并沒有這個i,只有實例化后,i才會真實存在 };struct B {int i; };void A::f() //函數(shù)是屬于A類的,而不屬于任何一個對象 {cout << i << endl;i = 20;cout << i << endl; }void f(struct B* p) //這是一個自由函數(shù),只要拿到struct B*類型的指針,就可以做事情 {p->i = 30;cout << p->i << endl; }int main(int argc, const char* argv[]) {A a;B b;A aa;a.i = 10;cout << a.i << endl;a.f(); //讓a這個對象做f()這個動作f(&b); //對b做事情cout << a.i << endl; //直接輸出a.iaa.f(); //aa里面的f()是類的函數(shù)return 0; }

? ? 執(zhí)行結(jié)果如下圖所示:

? ? 我們再嘗試輸出一些地址:

#include <iostream> using namespace std;class A { public:void f();int i; };void A::f() {i = 20;printf("A::f()--&i = %p\n", &i); }int main(int argc, const char* argv[]) {A a;printf("&a = %p\n", &a);printf("a.i = %p\n", &a.i);a.f();return 0; }

? ? 可以看到,&a的地址和&a.i的地址都是一樣的,這說明這個對象里面只有int i;這一個東西,再沒有其他東西了,這就是C++的對象安排;在A::f()里面也是一樣的結(jié)果,說明A::f()中的i就是&a.i

? ? 再做一個新的對象aa:

#include <iostream> using namespace std;class A { public:void f();int i; };void A::f() {i = 20;printf("A::f()--&i = %p\n", &i); }int main(int argc, const char* argv[]) {A a;A aa;printf("&a = %p\n", &a);printf("a.i = %p\n", &a.i);a.f();printf("&a = %p\n", &aa);printf("a.i = %p\n", &aa.i);aa.f();return 0; }

? ? 這可以充分說明,類A中的A::f()在被調(diào)用時,它是知道哪個對象(a或aa)在調(diào)用它:

? ? Call functions in a class

class Point { private:int x;int y; public:void print(); };Point::print() { }Point a; a.print();

? ? ◆ There is a relationship with the function be called and the variable calls it.

? ? ◆ The function itself knows it is doing something with the variable.

? ? this: the hidden parameter

? ? ◆ this is a hidden parameter for all member functions, with the type of the class

void Point::print() { } //Can be regarded as void Point::(Point* p) { }

? ? 我們嘗試打印出指針this的結(jié)果:

#include <iostream> using namespace std;class A { public:void f();int i; };void A::f() {i = 20;printf("A::f()--&i = %p\n", &i);printf("this = %p\n", this); }int main(int argc, const char* argv[]) {A a;printf("&a = %p\n", &a);printf("a.i = %p\n", &a.i);a.f();return 0; }

? ? ◆ To call the function, you must specify a variable

Point a; a.print(); //Can be regarded as Point::print(&a);

? ? ◆ Example: this.cpp

? ? this: pointer to the caller

? ? ◆ Inside member functions, you can use this as the pointer to the variable that calls the function.

? ? ◆ this is a natural local variable of all class member functions that you can not define, but can use it directly.

? ? ◆ Example: Integer.h, Integer.cpp

總結(jié)

以上是生活随笔為你收集整理的C++基础之成员变量的秘密的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

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