首页 > 代码库 > c++, 派生类的构造函数和析构函数
c++, 派生类的构造函数和析构函数
1.构造函数与析构函数不会被继承;[1]
不是所有的函数都能自动地从基类继承到派生类中的。构造函数和析构函数是用来处理对象的创建和析构的,它们只知道对在它们的特殊层次的对象做什么。所以,在整个层次中的所有的构造函数和析构函数都必须被调用,也就是说,构造函数和析构函数不能被继承。
另外,operator= 也不能被继承,因为它完成类似于构造函数的活动。
2.派生类的构函数被调用时,会先调用基类的其中一个构造函数,因为在派生类的构造函数中用了初始化表的方式调用了基类构造函数,默认不写时是调用了基类中可以不传参数的构造函数。
3.在派生类对象释放时,先执行派生类析构函,再执行其基类析构函数。
#include <iostream>using namespace std;#include <string>class Basic{public: string m_name; Basic(); Basic(string name); Basic(Basic& bc); ~Basic(); Basic& operator=(const Basic& bc) { cout << "Basic::operator=()\n"; this->m_name = bc.m_name; return *this; }};Basic::Basic(){ cout <<"Basic::Basic()"<<endl;}Basic::Basic(string name){ m_name = name ; cout <<"Basic::Basic(string)"<<"name:"<<m_name<<endl;}Basic::Basic(Basic &bc){ this->m_name = bc.m_name; cout <<"Basic::Basic(Basic&)"<<"name:"<<bc.m_name<<endl;}Basic::~Basic(){ cout<<"this is "<<m_name << "Basic::~Basic()"<<endl;;}class Derived:public Basic{public: int m_dx; Derived(); Derived(string name);//m_name ~Derived(); void show();};Derived::Derived(){ cout <<"Derived::Derived()"<<endl;}Derived::Derived(string name) :Basic(name){ cout <<"Derived::Derived(string)"<<"name:"<<m_name<<endl;}Derived::~Derived(){ cout <<"this is "<<m_name <<"Derived::~Derived()"<<endl;;}void Derived::show(){ cout<<"name: "<<m_name<<endl;}void test(){ Derived dc1("dc1"); cout<<""<<endl; Derived dc2("dc2");//m_bx cout<<""<<endl; dc1 = dc2 ; cout<<"next is dc1.show(): "; dc1.show(); cout<<""<<endl;}int main() { test(); while(1);}/**Basic::Basic(string)name:dc1Derived::Derived(string)name:dc1Basic::Basic(string)name:dc2 //生成派生类对象时,先调用基类的构造函数Derived::Derived(string)name:dc2 //在调用自身的构造函数Basic::operator=() //调用了基类的operator= ,并正确地对Derived::m_name进行了赋值。
//测试时,假如把基类的operator=实现为空函数,那么Derived对象也不能对Derived::m_name进行重新赋值。除非再手动实现Derived的operator=。
//operator= 只有一个,Drived中如果手动实现了,将会覆盖基类的=。就是说,不会执行基类的operator=。
next is dc1.show(): name: dc2 this is dc2Derived::~Derived() //析构和构造的调用顺序刚好相反。先调用自身的析构函数,再调用基类的析构函数。
this is dc2Basic::~Basic()
this is dc2Derived::~Derived()//在一个函数体中,先实现的对象后释放。
this is dc2Basic::~Basic()
**/
4.派生类构造函数首行的写法:
class Basic{public: int m_number; string m_name ; char m_sex;//‘m‘ ‘w‘ Basic(int n ,string name , char s);};Basic::Basic(int n,string name ,char s) :m_number(n) ,m_name(name) ,m_sex(s){// this->m_name = name;// this->m_number = n;// this->m_sex = s;}class Derived:public Basic{public: int m_age; string m_addr; Derived(int n,string name,char s,int a, string addr);};Derived::Derived(int n,string name,char s,int a, string addr) :Basic(n,name,s) ,m_age(a) ,m_addr(addr){}
参考:
1.构造与析构函数与 operator=不能被继承
http://www.cnblogs.com/findumars/p/3695340.html
c++, 派生类的构造函数和析构函数
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。