1.继承是什么?
下一级的类有上一级的类的共性且具有自己的特点
这样的类之间的关系叫做继承此时相对上一级为父类(基类),相对下一级为子类(派生类)
2.继承的意义
通过继承共性来减少多余代码
3.继承的基本语法
class 父类 {}
class 子类 :继承方式 父类 {}
示例:
#include<iostream>
using namespace std;
class father
{
public:
father()
{
num1 = 1;
num2 = 2;
}
int num1;
int num2;
};
class son:public father
{
public:
son()
{
num3 = 3;
}
int num3;
};
4.继承的方式
一共有三种:
所有继承方式子类均无法访问父类隐私权限内容
1)公共继承 所有成员权限均不变继承
2)保护继承 所有权限均变为保护权限
3)私有继承 所有权限均变为隐私权限
5.继承的对象模型
子类继承父类所有属性和行为(包括隐私权限下的)
注意:子类继承父类的隐私权限下的属性与行为在子类中不可访问而并非不继承
示例:
#include<iostream>
using namespace std;
class father
{
public:
father()
{
num1 = 1;
num2 = 2;
num3 = 3;
}
int num1;
int num2;
private:
int num3;
};
class son:public father
{
public:
son()
{
num4 = 4;
}
int num4;
};
int main()
{
son son1;
cout << sizeof(son) << endl;
return 0;
}
此时的输出结果为16
可见子类继承了父类的隐私权限下的成员变量
呢么当创建一个子类对象时父类子类构造函数与析构函数的调用顺序如何
示例:
#include<iostream>
using namespace std;
class father
{
public:
father()
{
cout << "父类构造函数的调用" << endl;
num1 = 1;
num2 = 2;
num3 = 3;
}
~father()
{
num1 = 1;
num2 = 2;
num3 = 3;
cout << "父类析构函数的调用" << endl;
}
int num1;
int num2;
private:
int num3;
};
class son:public father
{
public:
son()
{
cout << "子类构造函数的调用" << endl;
num4 = 4;
}
~son()
{
cout << "子类析构函数的调用" << endl;
}
int num4;
};
int main()
{
son son1;
return 0;
}
输出结果是:父类构造函数的调用
子类构造函数的调用
子类析构函数的调用
父类析构函数的调用
由此可见调用顺序
6.继承时非静态同名成员问题
1)同名成员变量
子类成员变量可直接访问
父类成员变量需加作用域
示例:
#include<iostream>
using namespace std;
class father
{
public:
father()
{
num1 = 1;
num2 = 2;
num3 = 3;
}
~father()
{
num1 = 1;
num2 = 2;
num3 = 3;
}
int num1;
int num2;
private:
int num3;
};
class son:public father
{
public:
son()
{
num1 = 4;
}
~son()
{
}
int num1;
};
int main()
{
son son1;
cout << son1.num1 << endl;
cout << son1.father::num1 << endl;
return 0;
}
7.继承时静态同名成员问题
通过对象访问时与6方法一致
通过类名访问
cout<<son::num1<<endl;//子类下的类名访问
cout<<son::father::num1<<endl;//父类下的类名访问
8.多继承
即一个类继承多个类
语法:class 子类: 继承方式 父类1 , 继承方式 父类2
示例
#include<iostream>
using namespace std;
class father1
{
public:
father1()
{
num1 = 1;
num2 = 2;
num3 = 3;
}
~father1()
{
num1 = 1;
num2 = 2;
num3 = 3;
}
int num1;
int num2;
private:
int num3;
};
class father2
{
public:
father2()
{
num1 = 2;
}
int num1;
};
class son:public father1,public father2
{
public:
son()
{
}
~son()
{
}
};
int main()
{
son son1;
cout << son1.father1::num1 << endl;
cout << son1.father2::num1 << endl;
return 0;
}
9.菱形继承问题
两个子类继承同一个父类,又有一个类继承这两个类
-
羊继承了动物的数据,驼同样继承了动物的数据,当草泥马使用数据时,就会产生二义性。
-
草泥马继承自动物的数据继承了两份,其实我们应该清楚,这份数据我们只需要一份就可以。
解决措施:使用虚继承
#include<iostream>
class Animal
{
public:
int m_Age;
};
//继承前加virtual关键字后,变为虚继承
//此时公共的父类Animal称为虚基类
class Sheep : virtual public Animal {};
class Tuo : virtual public Animal {};
class SheepTuo : public Sheep, public Tuo {};
void test01()
{
SheepTuo st;
st.Sheep::m_Age = 100;
st.Tuo::m_Age = 200;
cout << "st.Sheep::m_Age = " << st.Sheep::m_Age << endl;
cout << "st.Tuo::m_Age = " << st.Tuo::m_Age << endl;
cout << "st.m_Age = " << st.m_Age << endl;
}
int main() {
test01();
system("pause");
return 0;
}