子类对象包含多个组成部分(也就是多个子对象);
#include <iostream>
using namespace std;
class Father
{
public:
Father(int i):m_values(i)
{
cout << "Father(int i)" << endl;
}
virtual ~Father()
{
cout << "~Father()" << endl;
}
private:
int m_values;
};
class Son : public Father
{
public:
//通过子类的初始化列表给父类构造函数传参
Son(int i, int k):Father(i), m_value_b(k)
{
cout << "Son(int i, int k)" << endl;
}
~Son()
{
cout << "~Son()" << endl;
}
public:
int m_value_b;
};
int main()
{
//构造函数:先基类再子类
//析构函数:先子类再基类
Son* b = new Son(1, 2);
delete b;
return 0;
}
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << "Base()" << endl;
};
~Base()
{
cout << "~Base()" << endl;
};
};
class Father: public Base
{
public:
Father(int i):m_values(i)
{
cout << "Father(int i)" << endl;
}
virtual ~Father()
{
cout << "~Father()" << endl;
}
private:
int m_values;
};
class Son : public Father
{
public:
//通过子类的初始化列表给父类构造函数传参
Son(int i, int k):Father(i), m_value_b(k)
{
cout << "Son(int i, int k)" << endl;
}
~Son()
{
cout << "~Son()" << endl;
}
public:
int m_value_b;
};
int main()
{
Son* son = new Son(1, 2);
delete son;
return 0;
}
final:C++11中引入,加到基类后面,使其无法被继承;
class Base final
{
public:
Base()
{
cout << "Base()" << endl;
};
~Base()
{
cout << "~Base()" << endl;
};
};
class Father
//class Father : public Base 错误
{
public:
Father(int i):m_values(i)
{
cout << "Father(int i)" << endl;
}
virtual ~Father()
{
cout << "~Father()" << endl;
}
private:
int m_values;
};
基类对象能独立存在,也能作为派生类对象的一部分存在
Father* father = new Son(); //积累指针指向一个派生类对象
Father& q = *father; //基类引用绑定到派生类对象
Son son;
Father* father = &son; //可以
Son* p_son = father; // 非法,编译器通过静态类型推断转换合法性,发现基类不能转成派生类;如果基类中有虚函数,可以通过dynamic_cast转换;
Son* p_son = dynamic_cast<Son*> father;
并不存在从基类到派生类的自动类型转换
Son* son = new Father(); //非法
Father father;
Son &son = father; //非法,不能将基类转换成派生类,派生类的引用不能绑定到基类对象上
Son &son = &father; //非法,不能讲基类转成派生类,派生类指针不能指向基类地址
用派生类对象为一个基类对象初始化或者赋值的时候,只有该派生类对象的基类部分会被拷贝或者复制,派生类部分将被忽略掉;
Son son; //派生类对象;
Father father(son); //用派生类对象来定义并初始化基类对象,这个会导致基类的拷贝构造函数的执行
原文:https://www.cnblogs.com/Trevo/p/13343854.html