为什么类的大小只取决于数据成员而不是成员函数? [英] Why class size depend only on data members and not on member functions?
问题描述
我想知道关于类大小的详细描述。
我想知道是否只有数据成员&成员函数没有任何虚拟关键字,那么为什么类大小仅取决于数据成员。
例如:
I want to know the detail description on the size of a class. I want to know if there is only data members & member function without any virtual keyword then why the class size depends only on data members. For an eg:
class A {
int a;
public:
int display() {
cout << "A=" << a << endl;
}
};
当我检查 sizeof(A)
我发现它是4字节。为什么会这样?为什么成员函数对类A的大小没有影响?
When I check the sizeof(A)
i found that it is 4 byte. Why it is so? Why member function has no effect on the size of class A?
感谢
推荐答案
因为类的函数不保存在对象本身内。考虑到它在C编程方面,类 A 的每个函数都需要一个秘密参数, this 指针,因此实际上它们只是带有一个额外参数的函数。
Because the class's functions are not saved inside the object itself. Think of it in terms of C programming, every function of class A takes one secret parameter, the this pointer, so in actuality they are just functions with one extra parameter.
例如,假设它像这样:
int display(A* thisptr)
{
//do something
printf("%d",thisptr->a);
return;
}
因此,显示函数只保存一个简单的函数,
So the display function is saved as just a simple function with one extra parameter. The name though is mangled depending on the compiler.
我认为不同的规则适用于涉及函数指针的虚函数,但是我不确定也许别人可以启发我们就此事。
I believe that different rules apply for virtual functions which would involve function pointers but since I am not sure maybe someone else can enlighten us on this matter.
这篇关于为什么类的大小只取决于数据成员而不是成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!