C++基础之成员变量的秘密
? ? 執行結果如下圖所示:
? ? 我們再嘗試輸出一些地址:
#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()里面也是一樣的結果,說明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()在被調用時,它是知道哪個對象(a或aa)在調用它:
? ? 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的結果:
#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
總結
以上是生活随笔為你收集整理的C++基础之成员变量的秘密的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Win10的界面字体突然变大的解决办法
- 下一篇: Neutron学习笔记2-- Neutr