基本了解

  • 好处: 减少重复代码
  • 子类 <—> 派生类
  • 父类 <—> 基类

  1. #include <iostream>
  2. using namespace std;
  3. class Base {
  4. public:
  5. void run() {
  6. cout << "奔跑" << endl;
  7. }
  8. void eat() {
  9. cout << "吃" << endl;
  10. }
  11. };
  12. class Me :public Base {
  13. public:
  14. void hhdx() {
  15. cout << "哈哈大笑" << endl;
  16. }
  17. };
  18. int main() {
  19. Me me;
  20. me.eat();
  21. me.hhdx();
  22. me.run();
  23. }

继承方式

image.png


调用父类成员

  1. class Fther{
  2. public:
  3. int money = 100;
  4. void run(){
  5. cout << "基类的方法:run"
  6. };
  7. }
  8. class Son:public Fther{
  9. public:
  10. int money = 200;
  11. void run(){
  12. cout << "派生类的方法:run"
  13. }
  14. }
  15. int main(){
  16. Son s;
  17. //参数
  18. s.money; //本类的参数
  19. s.Fther:money; //父类的参数
  20. s.run(); //调用本类的方法
  21. s.Fther::run(); //调用父类的方法
  22. }

多继承

  1. class Fther1{
  2. public:
  3. int money1 = 100;
  4. }
  5. class Fther2{
  6. public:
  7. int money2 = 100;
  8. }
  9. class Son:public Fther1,public Fther2{
  10. public:
  11. int money3 = 200;
  12. }
  13. int main(){
  14. Son s;
  15. s.money1;
  16. s.money2;
  17. s.money3;
  18. }

虚继承

  • Base中的成员在Son中创建 , 然后Son继承的两个虚基类 的成员指向Son中成员的地址 ```cpp class Base{ public: int mag; };

//虚继承 class Fther1:virtual public Base{}; class Fther2:virtual public Base{};

class Son:public Fther1,public Fther2{}

int main(){ Son s;

  1. s.age;

} ```