Problem H: 类的多态

Problem H: 类的多态

Description :
设计一个父类A和三个子类A1、A2、A3,满足“Append Code”,完成程序。

类A存储一个整数值,类A1、A2、A3在类A上增加了一个整数值,输出由print()函数完成,且可以多态的调用print()函数。

Input
输入为八个整数。
Output
见样例。

Sample Input
1 2 3 4 5
10 20 30
Sample Output
A : 1
A1 : 2 10
A2 : 3 20
A2 : 4 30
A : 5

Append Code

#include <iostream>
using namespace std;
class A
{
public:
    int a;    
    A(int aa):a(aa){}    
    virtual void print()    
    {        
    cout<<"A : "<<a<<endl;    
    }
};
class A1:public A
{    
    int b;
public:     
    A1(int aa,int bb):A(aa),b(bb){}    
    void print()    
    {        
    cout<<"A1 : "<<a<<" "<<b<<endl;    
    }
}; 
class A2:public A
{    
    int c;
public:    
    A2(int aa,int cc):A(aa),c(cc){}    
    void print()    
    {        
    cout<<"A2 : "<<a<<" "<<c<<endl;    
    }
}; 
class A3:public A
{    
    int d; 
public:     
    A3(int aa,int dd):A(aa),d(dd){}    
    void print()    
    {        
    cout<<"A2 : "<<a<<" "<<d<<endl;    
    }
};   
int main()
{    
    int a, b, c, d, e, x, y, z;    
    cin >> a >> b >> c >> d >> e;    
    cin >> x >> y >> z;    
    A *p[5];   
    p[0] = new A(a);    
    p[1] = new A1(b, x);    
    p[2] = new A2(c, y);    
    p[3] = new A3(d, z);    
    p[4] = new A(e);     
    for(int i = 0; i < 5; i++)        
        p[i]->print();     
    for(int i = 0; i < 5; i++)        
        delete p[i];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值