Description
定义Base和Derived类,Derived类是Base类的子类,两个类都只有1个int类型的属性。定义它们的构造函数和析构函数,输出信息如样例所示。
Input
输入2个整数。
Output
见样例。
Sample Input
100
200
Sample Output
Base 100 is created.
Base 100 is created.
Derived 200 is created.
Derived 200 is created.
Base 100 is created.
Base 100 is created.
HINT
为什么还是在析构函数里面是created!
Append Code
int main()
{
int a, b;
cin>>a>>b;
Base base(a);
Derived derived(a, b);
return 0;
}
Accepted Code
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
class Base {
private:
int num1;
public:
Base(int n = 0) : num1(n) {
cout << "Base " << num1 << " is created.\n";
}
~Base() {
cout << "Base " << num1 << " is created.\n";
}
};
class Derived : public Base {
private:
int num2;
public:
Derived(int n1 = 0, int n2 = 0) : Base(n1), num2(n2) {
cout << "Derived " << num2 << " is created.\n";
}
~Derived() {
cout << "Derived " << num2 << " is created.\n";
}
};
int main()
{
int a, b;
cin>>a>>b;
Base base(a);
Derived derived(a, b);
return 0;
}
本文详细解析了C++中基类和派生类的构造函数与析构函数的实现过程,通过具体示例展示了如何定义带有int类型属性的Base和Derived类,并在构造和析构过程中输出相应的信息。
11万+

被折叠的 条评论
为什么被折叠?



