#include <iostream>
using namespace std
;
class CBase
{
protected:
int n
;
public:
CBase(int i
):n(i
) { }
void Print() { cout
<< "CBase:n=" << n
<< endl
; }
};
class CDerived:public CBase
{
public:
int v
;
CDerived(int i
):CBase(i
),v(2 * i
) { }
void Func() { } ;
void Print()
{
cout
<< "CDerived:n=" << n
<< endl
;
cout
<< "CDerived:v=" << v
<< endl
;
}
};
int main()
{
CDerived
objDerived(3);
CBase
objBase(5);
CBase
* pBase
= & objDerived
;
pBase
->Print();
cout
<< "1)------------" <<endl
;
CDerived
* pDerived
= (CDerived
*)(& objBase
);
pDerived
->Print();
cout
<< "2)------------" <<endl
;
objDerived
.Print();
cout
<< "3)------------" <<endl
;
cout
<< "sizeof(CBase)=" << sizeof(CBase
) << endl
;
cout
<< "sizeof(objCBase)=" << sizeof(objBase
) << endl
;
cout
<< "sizeof(CDerived)=" << sizeof(CDerived
) << endl
;
cout
<< "sizeof(*pDerived)=" << sizeof(*pDerived
) << endl
;
pDerived
->Print();
return 0;
}
/* 存放v位置并不属于objBase对象,可能属于其他变量;该值是不确定且不可预测的, 此处存放什么,不同编译器的处理办法不同; 如果该位置是操作系统规定不可访问的区域,那么程序就可能由于出错而中止 不同编译器在栈上放置局部变量的方式有所不同,用 DevC++编译本程序,输出结果就未必如此 */
转载请注明原文地址:https://blackberry.8miu.com/read-284.html