执行结果如下图所示:
我们再尝试输出一些地址:
#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
