注册 登录
编程论坛 VC++/MFC

有关类中的函数覆盖和多态(阿里云笔试题)

wlhdhn 发布于 2011-09-18 14:18, 1471 次点击
class BaseClass
{
public:
void myfun1()
{
myfun2();
cout<<"1"<<endl;
}
virtual void myfun2()
{
cout<<"2"<<endl;
}
};
class ExtClass:public BaseClass
{
public:
void myfun1()
{
myfun2();
cout<<"4"<<endl;
}
void myfun2()
{
cout<<"5"<<endl;
}
};
void myfunx(BaseClass *h)
{
h->myfun1();
h->myfun2();
}

int main(int argc,char *argv[])
{
  ExtClass h;
  h.myfun1();
  h.myfun2();
  cout<<"---"<<endl;
  myfunx(&h);
  return 0;
}
输出运行结果
运行后得到:
5
4
5
---
5
1
5
疑问是:myfun2实现了多态,用基类指针指向时,执行派生类的程序段,而myfun1没有实现多态,虽然是用基类指针指向派生类,但它仍指向基类的myfun1的程序段,可是在基类的myfun1中调用myfun2函数,怎么可能是执行了派生类的myfun2呢?
请各位指教!谢谢
4 回复
#2
玩出来的代码2011-09-18 21:48
这不正是多态的表现吗,要调用哪个函数永远都是根据他的实际类型来判断的,你传一个drived class的指针,调用的肯定是drived类得函数了。
#3
玩出来的代码2011-09-18 21:49
另外LZ是不是在csdn也问过阿里云笔试题,你的上个题在今天在csdn就出现了,同一个人?
#4
wlhdhn2011-10-16 20:53
关于编译环境为小端字节序的赋值问题
struct T_s1
    {
        char a;
        short b;
        char c;
    };
    union T_s2
    {
        int a;
        T_s1 b;
    };
    T_s2 s;
    s.a=0x11223344;
    cout<<hex<<s.b.a<<endl
        <<hex<<s.b.b<<endl
        <<hex<<s.b.c<<endl;

我在VC++6.0环境下的运行结果是:
                              D
                              1122
请问s.b.a的值为何是D?还有就是s.b.c为何没有值输出?
百思不得其解啊?
请大牛指点!!谢谢!!
#5
心灵百合2011-10-18 09:37
这好像是java吧
1