#include "stdio.h"
class B
{
char c;
public:
B( char n){c = n;}
virtual ~B(void)
{
X();
Y();
}
virtual void X(void)
{
printf("%c",c);
}
void Y(void)
{
printf("%c",c-1);
}
};
class D:public B
{
char c;
public:
D(char n):B(n+1){c = n;}
~D(void)
{
X();
Y();
}
void X(void)
{
printf("%c",c);
}
virtual void Y(void)
{
printf("%c",c-1);
}
};
B *newB(char c)
{
return new D(c);
}
int main(int argc, char* argv[])
{
B *pb= newB('X');
pb->X();
pb->Y();
delete pb;
return 0;
}
结果输出是:XXXWYX ,而不是:XXXXYX
为什么?
----------------解决方案--------------------------------------------------------
拜托你是用C++写的拉 它应该不包含#include "stdio.h" C++的头文件应该是#include <iostream.h>
----------------解决方案--------------------------------------------------------
int main(int argc, char* argv[])
{
B *pb= newB('X'); //D::c='X',B::c='Y'
pb->X(); //D::X(),,
pb->Y(); //B::Y();
delete pb; //(D)this->X(),this->Y(),
//(B)this->X(),this->Y(),
return 0;
}
这样可以解释通
this指针传到了析构函数
----------------解决方案--------------------------------------------------------
大姐,这是C区
----------------解决方案--------------------------------------------------------
#include "stdio.h"
class B
{
char c;
public:
B( char n){c = n;}
virtual ~B(void)
{
X();
Y();
}
virtual void X(void)
{
printf("B:X %c\n",c);
}
void Y(void)
{
printf("B:Y %c\n",c-1);
}
};
class D:public B
{
char c;
public:
D(char n):B(n+1){c = n;}
~D(void)
{
X();
Y();
}
void X(void)
{
printf("D:X %c\n",c);
}
virtual void Y(void)
{
printf("D:Y %c\n",c-1);
}
};
B *newB(char c)
{
return new D(c);
}
int main(int argc, char* argv[])
{
B *pb= newB('X');// D::c = 'X' B::c = 'Y'
pb->X();// virtual 起作用了,调用了子类的X()
pb->Y();// virtual 不起作用
delete pb;// 先析构D,再析构B,这个时候virtual不起任何作用,也就是楼上所说的this指针在起作用。
return 0;
}
输出结果如下:
D:X X
B:Y X
D:X X
D:Y W
B:X Y
B:Y X
[此贴子已经被作者于2007-9-20 14:59:29编辑过]
----------------解决方案--------------------------------------------------------