继承基类成员访问方式的变化
| 类成员/继承方式 | public继承 |
|---|---|
| 基类的public成员 | 派生类的public成员 |
| 基类的protected成员 | 派生类的protected成员 |
| 基类的private成员 | 在派生类不可见 |
| 类成员/继承方式 | protected继承 |
|---|---|
| 基类的public成员 | 派生类的protected成员 |
| 基类的protected成员 | 派生类的protected成员 |
| 基类的private成员 | 在派生类不可见 |
| 类成员/继承方式 | private继承 |
|---|---|
| 基类的public成员 | 派生类的private成员 |
| 基类的protected成员 | 派生类的private成员 |
| 基类的private成员 | 在派生类不可见 |
class Person
{
public:
void Print() //Person* this
{
cout << "name" << _name << endl;
cout << "age" <<_age <<endl;
}
protected:
string _name = "peter";
int _age = 18;
};
class Student : public Person
{
protected:
int _stuid;
};
class Teacher(派生类) : (继承方式)public Person(基类)
{
protected:
int _jobid;
};
int main()
{
Student s;
Teacher t;
s.Print();
t.Print();
return 0;
}
一般都使用public继承
class 默认继承为private,struct 默认继承为public。
class Student : protected Person
{
public:
void fun
{
cout << _age <<endl;(派生类不可见但存在)
}
protected:
int _stuid;
};
int main()
{
s.Print(); //&s Student*
}
切片(派生类可以赋值给基类的对象/指针/引用)
int main()
{
//对象
Student s;
Person p;
p = s;//切割、切片
//s=p;
//指针
Person* pp = &p;
Student* ps = &s;
pp = ps;
//ps = pp;
//引用
Student& rs1 = s;
Person& rs2 = s;
}
友元不能被继承
单继承: 一个子类只有一个直接父类的继承关系
多继承: 一个子类有两个或两个以上的直接父类的继承关系
菱形继承: 多继承的特例,缺点:有数据的冗余和二义性。
解决方法: 菱形虚拟继承
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class Person
{
public:
string _name;
};
class Student:public Person
{
private:
int _id;
};
class Teacher:public Person
{
private:
int _num;
};
class Learner:public Student ,public Teacher
{
private:
string _majorCourse;
};
int main()
{
Learner l;
//二义性
l._name = "John";
//冗余
l.Student::_name = "aaa";
l.Teacher::_name = "bbb";
return 0;
}
继承与组合:
1.public继承是一种is-a的关系
2.组合是一种has-a的关系
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
// Laptop和Lenovo Laptop和Hp构成is-a的关系
class Laptop
{
protected:
string _colour = "黑色"; // 颜色
string _size = "15"; // 尺寸
};
class Lenovo : public Laptop
{
public:
void Play()
{
cout << "打字顺畅-操控" << endl;
}
};
class Hp : public Laptop
{
public:
void Play()
{
cout << "好看-清晰" << endl;
}
};
// Tire和Laptop构成has-a的关系
class CPU
{
protected:
string _brand = "惠普"; // 品牌
};
class Laptop
{
protected:
string _colour = "黑色"; // 颜色
string _type = "暗影精灵"; // 类型
CPU _t; // 中央处理器
};
3.优先使用对象组合,而不是类的继承。
4.继承的耦合度高,有很强的依赖关系,而组合的耦合性低。
5.有时也要用继承,要实现多态必须用继承。

本文介绍了C++中的继承概念,包括基类成员访问方式的变化,强调友元不被继承。讨论了单继承、多继承和菱形继承的特点,其中菱形继承可能导致数据冗余和二义性问题,解决方案是采用菱形虚拟继承。此外,文章还对比了继承与组合,指出public继承体现is-a关系,组合体现has-a关系,并建议优先使用组合以降低耦合度,但在实现多态时仍需依赖继承。
4380

被折叠的 条评论
为什么被折叠?



