Problem B: 还会用继承吗?

Posted 一本故事i

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Problem B: 还会用继承吗?相关的知识,希望对你有一定的参考价值。

Problem B: 还会用继承吗?

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 2599  Solved: 1892
[Submit][Status][Web Board]

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

append.cc
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);
    }
}

  

#include <iostream>
using namespace std;
class Base
{
public :
    int num;
    Base(int t):num(t)
    {
        cout<<"Base = "<<num<<" is created."<<endl;
    }
    Base(const Base &p)
    {
        num=p.num;
        cout<<"Base = "<<num<<" is copied."<<endl;
    }
    ~Base()
    {
        cout<<"Base = "<<num<<" is erased."<<endl;
    }
};
class Derived:public Base
{
public :
    int num2;
    Derived(int a, int b):Base(a), num2(b)
    {
        cout<<"Derived = "<<num2<<" is created."<<endl;
    }
    Derived(const Derived &p):Base(p),num2(p.num2)//子类可以拷贝给基类
    {
        cout<<"Derived = "<<num2<<" is copied."<<endl;
    }
    ~Derived()
    {
        cout<<"Derived = "<<num2<<" 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);
    }
}

  

 

以上是关于Problem B: 还会用继承吗?的主要内容,如果未能解决你的问题,请参考以下文章

弄懂分治系列:换个模型,二分查找还会用吗?

上手体验Vue3 Vite的魅力(“快”的艺术),有了它,你还会用webpack吗?

子类可以同时继承父类的有参构造函数和无参函数吗,继承了无参函数还会再继承有参函数吗?

你真的知道async/await的好处嘛, 并且还会用好呢

你真的知道async/await的好处嘛, 并且还会用好呢

有趣的 C++ 代码片段,有啥解释吗? [复制]