一、继承类
在继承中,子类负责其直接基类的构造,至于如何构造需要看下面;
如何在子类中调用拷贝构造函数,看下面;
#include <iostream> #include <bits/stdc++.h> using namespace std; class Base { private: int _a; public: Base(int a=0):_a(a){cout<<"Base = "<<_a<<" is created."<<endl;} Base(const Base& p):_a(p._a){cout<<"Base = "<<_a<<" is copied."<<endl;} ~Base(){cout<<"Base = "<<_a<<" is erased."<<endl;} }; class Derived:public Base { private: int _b; public: Derived(int a=0,int b=0):Base(a),_b(b){cout<<"Derived = "<<_b<<" is created."<<endl;} Derived(const Derived& p):Base(p),_b(p._b){cout<<"Derived = "<<_b<<" is copied."<<endl;}//这里以后记住; ~Derived(){cout<<"Derived = "<<_b<<" 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); } }
二、封闭类
#include <iostream> #include <bits/stdc++.h> using namespace std; class Base { private: int _a; public: Base(int a=0):_a(a){cout<<"Base = "<<_a<<" is created."<<endl;} Base(const Base& p):_a(p._a){cout<<"Base = "<<_a<<" is copied."<<endl;} ~Base(){cout<<"Base = "<<_a<<" is erased."<<endl;} }; class Derived { private: Base c; int _b; public: Derived(int a=0,int b=0):c(a),_b(b){cout<<"Derived = "<<_b<<" is created."<<endl;} Derived(const Derived& p):c(p.c),_b(p._b){cout<<"Derived = "<<_b<<" is copied."<<endl;} ~Derived(){cout<<"Derived = "<<_b<<" 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); } }
文章来源: 区分好继承类和封闭类,两者有很大的区别