目录
一、继承与派生:
继承的概念:
继承是一种创建新类的方式,新建的类可以继承一个或多个类。++可以理解子承父业(儿子拥有父亲的所有属性)++
继承++描述的是类和类之间的关系++
++新建的类被称之为派生类(子)类,之前就存在的类被称之为基(父)类++
继承和派生:
- 继承和派生是同一个过程,从不同的角度来看的
一个新类从已经存在的类那里获取其已有的特性,这个叫继承(儿子继承父亲的财产)
从已存在的类产生一个子类,这个叫派生(父亲把财产给儿子)
二、继承方式:
定义一个新的类去继承另一个类
class A
{};
class B:public A //单继承
{};
class D
{};
class E
{};
class F:public D,public E//多继承
{};
class A
{}
class B:public A
{}
class C:public B
{}
class D:public C
{}
//多级继承,D拥有了A,B,C的所有属性
代码示例:
cpp
#include<iostream>
#include<string>
using namespace std;
class A {
public:
int a = 10;
};
class C {
public:
int c = 20;
};
class B :public A,public C
{
public:
void fun() {
cout << "a=" << a <<" "<<"c=" << c << endl;
}
};
class MYstring :public string {
public:
void fun() {
cout << this->c_str() << " " << this->length() << endl;
}
//符合开闭原则:允许功能增加不允许修改代码
};
int main() {
MYstring s1;//构造和析构不会被继承
s1.append("qwer");
cout << s1 << endl;
s1.fun();
B b;
b.fun();
}
三、继承之后:
继承之后子类访问父类成员:
1、如果++是public继承,那么就按父类的访问属性来访问++
2、是++其他访问属性,按严格的来++
++public < protected < private++
3、++私有成员能继承,但是要通过父类的接口访问++
4、如果++有同名成员,那么会隐藏父类的成员,默认调用的是子类的同名成员,要想访问父类的成员需要类名+作用域++
继承之后子类和父类的关系:
子类对象可以当作父类对象使用
子类对象可以对父类对象赋值,但是返回来不行
子类对象在定义的时候,会先调用父类构造,后调用子类构造
子类对象死亡的时候,先调用子类的析构,后调用父类的析构
要确保父类有对应的构造调用(可以通过初始化列表调用父类的构造)
代码示例:
头文件:
cpp
#pragma once
#include<iostream>
using namespace std;
class person1
{
public:
person1() {
cout << "person1的构造" << endl;
}
void song() {
cout << "我会唱歌" << endl;
}
~person1() {
cout << "person1的析构" << endl;
}
};
class person2 :person1
{
public:
person2(int x) {
cout << "person2的带参构造"<<x << endl;
}
void dance() {
cout << "我会跳舞" << endl;
}
~person2() {
cout << "person2的析构" << endl;
}
};
class person3 :public person2
{
public:
person3():person2(10) {
cout << "person3的构造" << endl;
}
void rap() {
cout << "我会rap" << endl;
}
~person3() {
cout << "person3的析构" << endl;
}
};
class person4
{
public:
person3 *person;
};
class cperson {
public:
cperson(int x) {
cout << "cperson的构造" << endl;
}
};
class cperson2 : public person2, public cperson
{
public:
cperson2() :cperson(20),person2(10){
cout << "cperson2的构造" << endl;
}
};
源文件:
cpp
#include<iostream>
using namespace std;
class father {
public:
int a = 10;
void fun1() {
cout << a << " " << b << " " << c << endl;
}
void set(int x) {
c = x;
}
protected:
int b = 20;//类外不允许访问
private:
int c = 30;//子类不可访问
};
class son :public father {
public:
void fun(int x,int y,int z) {
a = x;
b = y;
set(z);
}
};
int main() {
son s;
s.fun1();
s.fun(1, 2, 3);
s.set(3);
s.fun1();
s.a;
return 0;
}
四、菱形继承:
C++中的菱形继承是指++一个派生类同时继承自两个直接或间接基类,而这两个基类又共同继承自同一个基类的情况++
这种继承关系++会导致派生类中包含了同名的基类成员, 从而引发命名冲突和多次继承同一成员的问题++
代码示例:
cpp
#include<iostream>
using namespace std;
class A {
public:
int a = 1;
};
class B :virtual public A {
public:
B() { a = 2; }
};
class C :virtual public A {
public:
C() { a = 3; }
};
class D :public B, public C {
};
//虚继承
int main() {
A* P1 = new A;
B* P2 = new B;
C* P3 = new C;
D* P4 = new D;
cout << P4->C::a << endl;//明确调用的是什么的a
cout << P4->a << endl;
}