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

    科技2022-08-23  97

    #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() //函数是属于A类的,而不属于任何一个对象 { cout << i << endl; i = 20; cout << i << endl; } void f(struct B* p) //这是一个自由函数,只要拿到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.i aa.f(); //aa里面的f()是类的函数 return 0; }

        执行结果如下图所示:

        我们再尝试输出一些地址:

    #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

    Processed: 0.024, SQL: 9