返回信息流代码:
#include <iostream.h>
class Base
{
public:
virtual void f(float x)
{
cout <<"Base::f(float)"<<x<<endl;
}
void g(float x)
{
cout <<"Base::g(float)"<<x<<endl;
}
void h(float x)
{
cout<<"Base::h(float)"<<x<<endl;
}
};
class Derived :public Base
{
public:
virtual void f(float x)
{
cout <<"Derived::f(float)"<<x<<endl;
}
void g(int x)
{
cout <<"Derived::g(int)"<<x<<endl;
}
void h(float x)
{
cout<<"Derived::h(float)"<<x<<endl;
}
};
int main(void)
{
Derived d;
Base *pb =&d;
Derived *pd=&d;
pb->f(3.14f);
pd->f(3.14f);
pb->g(3.14f);
pd->g(3.14f);
pb->h(3.14f);
pd->h(3.14f);
return 0;
}
输出是什么?why?
这是一条镜像帖。来源:北邮人论坛 / cpp / #20663同步于 2009/3/23
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
请教个继承的题
sgxg
2009/3/23镜像同步8 回复
订阅后,新回复会通过你的通知中心匿名送达。
8 条回复
Derived
Derived
base
derived
base
derived
g()和h()有什么区别?没看出来。
ps. 知道原因,不知道怎么说。(还算是不知道吧。)
pb->f(3.14f); //Derived::f(float)3.14
pd->f(3.14f); //Derived::f(float)3.14
pb->g(3.14f); //Base::g(float)3.14
pd->g(3.14f); //Derived::g(int)3.14
没看出来g()和h()有什么区别
【 在 sgxg (水果香瓜) 的大作中提到: 】
: 代码:
: #include <iostream.h>
: class Base
: ...................
因为h()是non-virtual的,h()是静态绑定的,pb指向的是base类型,就调用base的
【 在 sgxg (水果香瓜) 的大作中提到: 】
: pb->h(3.14f)为什么是base,而不是derived?
不好意思,写错了:Derived类中的g参数应是int,已经改过来了
【 在 DarkIce 的大作中提到: 】
: pb->f(3.14f); //Derived::f(float)3.14
: pd->f(3.14f); //Derived::f(float)3.14
: pb->g(3.14f); //Base::g(float)3.14
: ...................
明白了,谢谢大牛:)
【 在 DarkIce 的大作中提到: 】
: 因为h()是non-virtual的,h()是静态绑定的,pb指向的是base类型,就调用base的
pb->g(3.14f); //Base::g(float)3.14
pd->g(3.14f); //Derived::g(int)3
pb->h(3.14f); //Base::h(float)3.14
pd->h(3.14f); //Derived::h(float)3.14
【 在 sgxg (水果香瓜) 的大作中提到: 】
: 不好意思,写错了:Derived类中的g参数应是int,已经改过来了