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;
}


相关文章
|
2月前
|
编译器 C++
【C++】详解C++的继承
【C++】详解C++的继承
|
3月前
|
编译器 数据安全/隐私保护 C++
c++primer plus 6 读书笔记 第十三章 类继承
c++primer plus 6 读书笔记 第十三章 类继承
|
8天前
|
C++
C++(二十)继承
本文介绍了C++中的继承特性,包括公有、保护和私有继承,并解释了虚继承的作用。通过示例展示了派生类如何从基类继承属性和方法,并保持自身的独特性。此外,还详细说明了派生类构造函数的语法格式及构造顺序,提供了具体的代码示例帮助理解。
|
29天前
|
安全 Java 编译器
|
2月前
|
存储 Java 程序员
【c++】继承深度解剖
【c++】继承深度解剖
25 1
|
2月前
|
存储 编译器 数据安全/隐私保护
|
2月前
|
Java C++ 运维
开发与运维函数问题之C++中有哪些继承方式如何解决
开发与运维函数问题之C++中有哪些继承方式如何解决
21 0
|
3月前
|
C++
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)
|
3月前
|
C++
【C++】学习笔记——继承_2
【C++】学习笔记——继承_2
28 1
|
3月前
|
编译器 C++
C++中的继承
C++中的继承
32 1