系列文章目录
首先看这样一个类定义:Book继承自Library_materials
class Library_materials
{
public:
Library_materials(/* args */){cout<<"Library_materials construct"<<endl;};
~Library_materials(){cout<<"Library_materials deconstruct"<<endl;};
void check_in(){cout<<"Library_materials check in."<<endl;};
};
class Book:public Library_materials
{
public:
Book(/* args */){cout<<"Book construct"<<endl;};
~Book(){cout<<"Book deconstruct"<<endl;};
void check_in(){cout<<"Book check in."<<endl;};
};
void test_polymorphic(){
Library_materials thing1;
Book book;
Library_materials &thing2=book;
std::cout<<"==========================="<<endl;
std::cout<<"book ptr:"<<&book<<endl;
std::cout<<"thing2 ptr:"<<&thing2<<endl;
thing1 = book;
thing1.check_in();
thing2.check_in();
book.check_in();
std::cout<<"==========================="<<endl;
}
上面这段代码中,首先我们看构造过程。
- thing1:调用基类构造
- book: 先调用基类构造,在调用派生类构造
- thing2:引用类型,不调用构造
接下来分析check_in重写的调用过程。
- thing1:调用基类check_in
- thing2:调用基类check_in(虽然thing2和book地址一样)
- book:调用派生类check_in
测试的输出如下:
Library_materials construct
Library_materials construct
Book construct
===========================
book ptr:0x7fffffffd80f
thing2 ptr:0x7fffffffd80f
Library_materials check in.
Library_materials check in.
Book check in.
===========================
Book deconstruct
Library_materials deconstruct
Library_materials deconstruct