OJ 1814 Problem A 还会用继承吗?

Description

定义一个Base类,包括1个int类型的属性,以及满足输出格式要求的构造函数、拷贝构造函数和析构函数。

定义Base类的子类Derived,包括1个int类型的属性, 以及满足输出格式要求的构造函数、拷贝构造函数和析构函数。

Input

第1行N>0表示测试用例个数。

每个测试包括2个int类型的整数。

Output

见样例。

Sample Input

1
10 20

Sample Output

Base = 10 is created.
Base = 10 is copied.
Base = 10 is created.
Derived = 20 is created.
Base = 10 is copied.
Derived = 20 is copied.
Derived = 20 is erased.
Base = 10 is erased.
Derived = 20 is erased.
Base = 10 is erased.
Base = 10 is erased.
Base = 10 is erased.

HINT

Append Code

int main()
{
    int cases, data1, data2;
    cin>>cases;
    for (int i = 0; i < cases; i++)
    {
        cin>>data1>>data2;
        Base base1(data1), base2(base1);
 
        Derived derived1(data1, data2), derived2(derived1);
    }
}

Accepted Code

#include <iostream>
using namespace std;

class Base {
protected:
    int num;
public:
    Base(int n = 0) : num(n) { cout << "Base = " << num << " is created." << endl; }
    Base(Base &B) : num(B.num) {  cout << "Base = " << num << " is copied." << endl; }
    ~Base() { cout << "Base = " << num << " is erased." << endl; }
};
class Derived : public Base {
private:
    int num1;
public:
    Derived(int n1 = 0, int n2 = 0) : Base(n1), num1(n2) { cout << "Derived = " << num1 << " is created." << endl; }
    Derived(int n1 = 0) : num1(n1) { cout << "Derived = " << num1 << " is created." << endl; }
    Derived(Derived &D) : Base(D) , num1(D.num1) { cout << "Derived = " << num1 << " is copied." << endl; }
    ~Derived() { cout << "Derived = " << num1 << " is erased." << endl; }
};
int main()
{
    int cases, data1, data2;
    cin>>cases;
    for (int i = 0; i < cases; i++)
    {
        cin>>data1>>data2;
        Base base1(data1), base2(base1);

        Derived derived1(data1, data2), derived2(derived1);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值