022:看上去像多态

题目:

http://cxsjsxmooc.openjudge.cn/2021t3springall2/022/

分析:

这题还挺有意思的,利用了基类指针能指向派生类成员,但只能访问基类部分数据的这个特点,实际上像题目上用基类指针指向派生类对象但又不是多态的做法是错误的,不过郭炜老师的题中这样的题目比比皆是,利用这种“错误”用法去让我们记住这种用法是不正确的。

参考代码:

//emmm...大家忽略我山寨的英语注释,因为写代码时切换中英输入法挺麻烦的,顺便还能练习一下哈,大伙凑合凑合。
#include <iostream>
using namespace std;
class B {
private:
    int nBVal;
public:
    void Print()
    { cout << "nBVal="<< nBVal << endl; }
    void Fun()
    {cout << "B::Fun" << endl; }
    B ( int n ) { nBVal = n;}
};
// 在此处补充你的代码
class D:public B{
private:
    int nDVal;
public:
    D ( int n ):B(3 * n) { nDVal = n;}
    void Print()
    {
        B::Print();
        cout << "nDVal="<< nDVal << endl;
    }
    void Fun()
    {cout << "D::Fun" << endl; }
};


int main() {
    B * pb; D * pd; //define derived class D form B
    D d(4); d.Fun(); //define cover function Fun() of class D
    pb = new B(2); pd = new D(8);//class D's construction function
    pb -> Fun(); pd->Fun();
    pb->Print (); pd->Print (); //define cover function Print() of class D
    //according to the output, B.Print() will print "nBVal=24" and  "nDVal=8"
    pb = & d; //Decided that class D must form B
    //the class D derived from class B, so pointer pb can point to variable d(class D)
    //but int that time pb just can visit the elements from class B of class D.
    //we can change the nBVal in class D only in initialization.
    pb->Fun();
    pb->Print();
    return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值