022:看上去像多态
程序员文章站
2024-03-17 17:53:46
...
题目:
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;
}