C++中的虚函数
2010-10-15 09:07:57 来源:Web开发网三、虚函数在内存中的结构
1.我们先看一个例子:
#include "iostream.h"
#include "string.h"
class A {
public:
virtual void fun0() { cout << "A::fun0" << endl; }
};
int main(int argc, char* argv[])
{
A a;
cout << "Size of A = " << sizeof(a) << endl;
return 0;
}
结果如下:Size of A = 4
2.如果再添加一个虚函数:virtual void fun1() { cout << "A::fun" << endl;}
得到相同的结果。如果去掉函数前面的virtual修饰符class A {
public:
void fun0() { cout << "A::fun0" << endl; }
};
int main(int argc, char* argv[])
{
A a;
cout << "Size of A = " << sizeof(a) << endl;
return 0;
}
结果如下:Size of A = 1
3.在看下面的结果:
class A {
public:
virtual void fun0() { cout << "A::fun0" << endl; }
int a;
int b;
};
int main(int argc, char* argv[])
{
A a;
cout << "Size of A = " << sizeof(a) << endl;
return 0;
}
结果如下:Size of A = 12
其实虚函数在内存中结构是这样的:
图一
更多精彩
赞助商链接