公共函数的调用原理:
c++设置了 this 指针,this 指针指向调用该函数的不同对象。当 t 调用dis()函数时,this 指向 t。当 t1 调用 dis()函数时,this 指向 t1;
相关注意:
1.不论成员函数在类内定义还是在类外定义,成员函数的代码段都用同一种方式存储
2.应当说明,常说的“某某对象的成员函数”,是从逻辑的角度而言的,而成员函数的存储方式,是从物理的角度而言的,二者是不矛盾的。类似于二维数组是逻辑概念,而物理存储是线性概念一样。
3.每个对象所占用的存储空间,只是该对象的数据部分所占用的存储空间,而不包括函数代码所占用的存储空间
4.在对象调用函数的同时,向该函数传递了该对象的指针,该指针就是this
#include "stdafx.h"
#include <iostream>
using namespace std;
class Time
{
public:
Time(int h, int m, int s)
:hour(h), minute(m), sec(s){}
void display() //void dis(Time *p)
{
cout << "this=" << this << endl;
cout <<this->hour<<":"<<this->minute<<":"<<this->sec<< endl;
//可以不写this-> 因为对象调用同时 系统默认将this传入到函数中
}
private:
int hour;
int minute;
int sec;
};
int _tmain(int argc, _TCHAR* argv[])
{
Time t(1, 2, 3), t1(2, 3, 4), t2(3, 4, 5);
cout << sizeof(Time) << "--" << sizeof(t) << endl;
cout << "&t" << &t << endl;
t.display();
cout << "&t1" << &t1 << endl;
t1.display();
cout << "&t2" << &t2 << endl;
t2.display();
return 0;
}
各对象与数据和函数之间的关系
