作者在 2007-12-20 09:53:36 发布以下内容
代码如下:(基类base,c1继承base,c2继承c1,c3继承c2)
#include <stdio.h> class base { int a; public: int b; void display() { printf("a=%d b=%d c=%d\n",a,b,c); } base() { a=1; b=2; c=3; } ~base(){} protected: int c; }; class c1:public base { int a1; public: c1() { base(); a1=11; } void display() { base::display(); printf("class c1:a1=%d\n",a1); } }; class c2:public c1 { int a2; public: c2() { c1(); a2=111; } void display() { c1::display(); printf("class c2:a2=%d\n",a2); } }; class c3:public c2 { int a3; public: void display() { c2::display(); printf("class c3:a3=%d\n",a3); } }; void main() { c1 c11; c11.display(); base* base1=new base(); base1->display(); ((c1*)base1)->display(); c2 c21; c21.display(); ((c2*)base1)->display(); ((c3*)base1)->display(); } |
VC6输出结果:
a=1 b=2 c=3
class c1:a1=11
a=1 b=2 c=3
a=1 b=2 c=3
class c1:a1=-33686019
a=1 b=2 c=3
class c1:a1=11
class c2:a2=111
a=1 b=2 c=3
class c1:a1=-33686019
class c2:a2=0
a=1 b=2 c=3
class c1:a1=-33686019
class c2:a2=0
class c3:a3=0
红色部分挺奇怪的,我觉得应该是个随机的数字,而不是0才对~
呃,研究中....
=================================================
问题解决,其实0也是一个随机数....
当我再继承出来c4和c5之后,a4和a5都不是0
本来a2=0的时候我就有考虑是不是刚好随机出来个0,就再写了一个c3试试看,结果还是0,所以比较不解,想着总不会那么巧,刚好都是0.
唉,还是不够严谨