先来一个类的成员函数的例子:
#include<iostream>
using namespace std;
class MyTime {
private:
int hour;
int minute;
int second;
public:
void settime(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}
void display() {
cout << hour << ":" << minute << ":" << second << endl;
}
};
int main() {
MyTime morning;
morning.settime(9, 20, 50);
morning.display();
system("pause");
return 0;
}
为什么类中的成员函数不占用对象空间呢,正式因为类中的成员函数其实就是全局函数或者说是该命名空间中的全局函数,只不过把他放到了类中而已,他的本质转换成C语言的结构体是这样的:
#include<stdio.h>
using namespace std;
struct MyTime {
int hour;
int minute;
int second;
};
void settime(struct MyTime* mt, int h, int m, int s) {
mt->hour = h;
mt->minute = m;
mt->second = s;
}
void display(struct MyTime* mt) {
printf("%d:%d:%d\n", mt->hour, mt->minute, mt->second);
}
int main() {
struct MyTime morning;
settime(&morning, 9, 20, 50);
display(&morning);
system("pause");
return 0;
}
可以看到用C语言的结构体来实现,函数就是全局函数,只不过在函数中多了一个参数struct MyTime* mt,实际上C++中的类成员函数中也是有这么一个参数的,只不过被隐藏了,这个被隐藏的就是this指针。两个打印出的结果都是:
理解了类成员函数的原理,就自然明白了为什么类成员并不占用对象空间。