继承相当于作用域:
继承中所有成员属性都会被子类继承;
父类中的私有成员,会被继承,但无法访问;
继承中先构造父类,再构造子类,析构则反之;
继承同名成员(属性和函数)时,子类的成员直接访问 s.m_a;,父类 s.Base::m_a;
虚继承解决了菱形继承中子类继承两份相同数据的问题;
实际开发中避免使用多继承;
继承中的对象模型:
静态成员访问方式:和非静态成员一样,只是静态成员有两种处理方式;
静态属性的访问
静态函数访问:
多继承语法
菱形继承问题:
#include<iostream>
#include<string>
using namespace std;
//菱形继承;
//animal calss
class Animal
{
public:
int m_age;
};
//sheep class 继承 animal
//菱形继承时用virtual
class Sheep :virtual public Animal
{
public:
string m_name = "sheep";
};
//tuo class 继承 animal
class Camel :virtual public Animal
{
public:
string m_name = "camel";
};
//sheepTuo class 继承 sheep ,tuo类
class SheepCamel :public Sheep, public Camel {};
int main()
{
SheepCamel s;
s.Sheep::m_age = 18;
s.Camel::m_age = 20;
//当菱形继承,两个父类拥有相同数据,virtual会使数据实体只有一个;
cout << "s.Sheep::m_age sheep's age is " << s.Sheep::m_age << endl;
cout << "s.Tuo::m_age tuo's age is " << s.Camel::m_age << endl;
cout << "sheeptuo's age is " << s.m_age << endl;
//两个父类成员名相同,则需要用作用域区分;
cout << s.Sheep::m_name << endl;
cout << s.Camel::m_name << endl;
system("pause");
return 0;
}