区分好继承类和封闭类,两者有很大的区别

匿名 (未验证) 提交于 2019-12-03 00:21:02

一、继承类
在继承中,子类负责其直接基类的构造,至于如何构造需要看下面;
如何在子类中调用拷贝构造函数,看下面;

#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);     } }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!