C++单继承和多继承
C++单继承和多继承
- 继承
- 单继承
- 写法
- 继承中构造函数的写法
- 写法
- 构造和析构的顺序问题
- 多继承
继承
1.继承,主要是遗传学中的继承概念
2.继承的写法,继承中的权限问题
3.继承中的构造函数的写法继承:子类没有新的属性,或者行为的产生
父类
子类派生:子类有新的属性产生
基类
派生类
单继承
只有父类的继承,称之为单继承
写法
#include<iostream>
#include<string>
using namespace std;
class father //父类
{
};
class son : public father //class 子类:继承方式 父类
{
};
//继承方式可分为:public, private, protected
int main()
{
system("pause");
return 0;
}
继承方式的作用:
继承方式 private public protected
public private public protected
private private private private
protected private protected protected
由此可见,继承方式为public父类中的权限不变
继承方式为private, 父类中的权限全变为private
继承方式为protected , 父类中的public和protected 都变为protected ,private不变注意:1.继承的属性无论被继承多少次,都存在,A被B继承,B被C继承,C被D继承,D包含ABC中所有的属性
2.继承不易多次继承,防止子类臃肿
3.私有的方式继承,可以阻断父类的属性
继承中构造函数的写法
写法
写法:子类必须先构造父类对象(子类必须调用父类的构造函数)
注意:
1.调用父类的构造函数必须使用初始化参数列表
2.如果你子类想写无参构造函数,那么你父类中必须要有无参构造函数,不然就会报错。
#include<iostream>
#include<string>
using namespace std;
class A
{
public:
A(){}
A(int a) : a(a)
{
cout << a << endl;;
}
int a = 1;
};
class B : public A
{
public:
B() {}
B(int a, int b):A(a),b(b)
{
}
void print()
{
cout << a << b << endl;
}
private:
int b = 2;
};
int main()
{
B mm(2, 4); //先构造父类的对象,在构造子类的对象
mm.print();
system("pause");
return 0;
}
构造和析构的顺序问题
1.构造顺序:如果这个son继承了father这个类,先构造父类的对象,再构造自身的对象
2.构造顺序与析构顺序相反
多继承
多继承就是存在两个及两个以上的父类
权限问题和构造函数跟单继承一样
#include<iostream>
#include<string>
using namespace std;
class father
{
public:
father(string Father): Father_name(Father_name){}
protected:
string Father_name;
};
class mother
{
public:
mother(string Mother_name) : Mother_name(Mother_name){}
protected:
string Mother_name;
};
class son : public father, public mother
{
public:
son(string Father_name, string Mother_name, string Son_name) : father(Father_name), mother(Mother_name)
{
this->Son_name = Father_name + Mother_name;
}
void print()
{
cout << Father_name << Mother_name << endl; //如果Father_name 是私有权限无法访问,这里是保护权限,可以访问
cout << this->Son_name << endl;
}
private:
string Son_name;
};
int main()
{
son m("温柔", "了", "岁月");
m.print();
system("pause");
return 0;
}