存个代码
#include <bits/stdc++.h>
using namespace std;
class Parent {
protected:
int pnum;
public:
Parent(){
pnum = 0;
cout << "调用Parent的无参构造函数" << endl;
}
Parent(int pnum) {
this->pnum = pnum;
cout << "调用Parent的有参构造函数" << endl;
}
~Parent() {
cout << "调用Parent的析构函数" << endl;
}
void show() {
cout << pnum << endl;
}
};
class Child : public Parent {
protected:
int cnum;
public:
Child() : Parent() {
pnum = 0;
cnum = 0;
cout << "调用Child的无参构造函数" << endl;
}
Child(int pnum, int cnum) : Parent(pnum) {
this->cnum = cnum;
cout << "调用Child的有参构造函数" << endl;
}
~Child() {
cout << "调用Child的析构函数" << endl;
}
void show() {
cout << pnum << ' ' << cnum << endl;
}
};
class B {
public:
int bnum;
B() {
bnum = 0;
cout << "调用B的无参构造函数" << endl;
}
B(int bnum) {
this->bnum = bnum;
cout << "调用B的有参构造函数" << endl;
}
~B() {
cout << "调用B的析构函数" << endl;
}
void show() {
cout << bnum << endl;
}
};
class A : public Parent {
private:
int anum;
B b; // A类中定义了B类的对象
public:
A() : Parent(), b() {
pnum = 0;
b.bnum = 0;
anum = 0;
cout << "调用A的无参构造函数" << endl;
}
A(int pnum, int bnum, int anum) : Parent(pnum), b(bnum) {
this->anum = anum;
cout << "调用A的有参构造函数" << endl;
}
~A() {
cout << "调用A的析构函数" << endl;
}
void show() {
cout << pnum << ' ' << b.bnum << ' ' << anum << endl;
}
};
int main() {
Parent p1;
Parent p2(5);
p1.show();
p2.show();
cout << "****************" << endl;
Child c1;
Child c2(1, 2);
c1.show();
c2.show();
cout << "****************" << endl;
B b1;
B b2(10);
b1.show();
b2.show();
cout << "****************" << endl;
A a1;
A a2(5, 6, 7);
a1.show();
a2.show();
return 0;
}
结果