-
2009-10-16
polymiorphism of C++ - [C++]
版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://zongtongyi.blogbus.com/logs/48515553.html
There days, I joined a written examination, and I found a intereting topic about C++'s polymiorphism, so I wrote some extend codes after I came back, here it is:
#include <iostream>
using namespace std;
class Base
{
public:int b;
virtual void f(void){cout << "Base::f(int) " << endl;}
};
class Derive:public Base
{
public:int d;
virtual void f(void){cout << "Derive::f(int) " << endl;}
};
int main()
{
Base b;
Derive d;
Base *pb = &d;
Base &rb = d;
b.f();
d.f();
pb->f();
rb.f();
cout <<sizeof(int)<<endl
<<sizeof(Base) << endl
<<sizeof(*pb) << endl
<<sizeof(Derive)<<endl;
return true;
}Compiled on Ubuntu 8.04 、 g++ .
the f(void) with or without "virtual" will change the output1、without virtual, the output will be :
Base::f(int)
Derive::f(int)
Base::f(int)
Base::f(int)
4
4
4
8because the Derive overlap Base's f(void), no matter pointer or refer
sizeof(Base) is "int b" 's size, it's 4; sizeof(*pb) is the same to sizeof(Base); sizeof(Derive) is "int b" plus "int d", so it's 8.
2、with virtual, the output will be :Base::f(int)
Derive::f(int)
Derive::f(int)
Derive::f(int)
4
8
8
12because the Derive overload Base's f(void), no matter pointer or refer
sizeof(Base) is "int b" plus "virtual f(void)" 's pointer, pointer's size is 4; sizeof(*pb) is the same to sizeof(Base); sizeof(Derive) is "int b" plus "int d" plus "virtual f(void)" 's pointer, just one pointer for "virtual f(void)".
随机文章:
让人大彻大悟的孔子临终遗言[转] 2009-05-25〔zt〕c/c++编程基础篇之浅析堆&栈〔精〕 2007-04-20Linux 用户态与内核态的交互[转]〔保留〕 2007-02-01http隧道[转] 2006-07-22[转载]编程修养-------精品(一) 2006-04-30
收藏到:Del.icio.us







