继承是面向对象设计中非常重要的概念,在C++中尤为重要,C++中的继承比其它语言要更为复杂。

继承的好处

通过继承可以让子类拥有父类的所有成员变量以及函数,从而达到重用代码的目的。

关系描述:
继承代表 is a 的关系。比如:猫是动物

Snipaste_2021-08-07_15-03-54.png

  1. #include <iostream>
  2. //Animal
  3. class Animal {
  4. public:
  5. int m_id;
  6. void walking(){
  7. std::cout << "Animal 在走 " << std::endl;
  8. }
  9. void run(){
  10. std::cout << "Animal 在🏃🏃🏃🏃🏃🏃 " << std::endl;
  11. }
  12. };
  13. // Cat类
  14. class Cat : public Animal{
  15. public:
  16. int m_weight;
  17. int m_height;
  18. void walking(){
  19. std::cout << "Cat 在走 " << std::endl;
  20. }
  21. void run(){
  22. std::cout << "Cat 在🏃🏃🏃🏃🏃🏃 " << std::endl;
  23. }
  24. };
  25. int main(int argc, const char * argv[]) {
  26. Cat cat;
  27. cat.m_id = 10; //访问父类的成员变量
  28. cat.m_weight = 20;
  29. cat.m_height = 30;
  30. cat.run();
  31. return 0;
  32. }

不像其它语言中的继承关系,C++中的类默认是没有继承其它基类的。而像Java、Object-C是有默认继承基类的。
Java里面定义一个类,默认是继承Object。

  1. public class Animal { //默认是继承Object的
  2. }
  3. public class Cat extends Animal {
  4. }

iOS中的Object-C中定义一个类默认是继承NSObject类。

  1. @interface Animal //默认是继承NSObject类
  2. @end
  3. @interface Cat : Animal
  4. @end

继承情况下,对象的内存是如何排布的

考虑下面的代码,whiteCat的成员变量(m_id、m_weight、m_height),内存中谁排在前面,谁排在后面?

  1. #include <iostream>
  2. //Animal
  3. class Animal {
  4. public:
  5. int m_id;
  6. };
  7. // Cat类
  8. class Cat : public Animal{
  9. public:
  10. int m_weight;
  11. };
  12. //白猫
  13. class WhiteCat: public Cat {
  14. public:
  15. int m_height;
  16. };
  17. int main(int argc, const char * argv[]) {
  18. WhiteCat *whiteCat = new WhiteCat();
  19. whiteCat->m_weight = 20; //访问父类的成员变量
  20. whiteCat->m_height = 30;
  21. whiteCat->m_id = 10;
  22. std::cout << &(whiteCat->m_id) << std::endl; //0x10052a7f0
  23. std::cout << &(whiteCat->m_weight) << std::endl; //0x10052a7f4
  24. std::cout << &(whiteCat->m_height) << std::endl; //0x10052a7f8
  25. return 0;
  26. }

结论:父类的成员变量在内存中会排在前面,子类的排在后面。

对象 成员变量 内存地址 内存数据
&whiteCat &(whiteCat->m_id) 0x10052a7f0 10
&(whiteCat->m_weight) 0x10052a7f4 20
&(whiteCat->m_height) 0x10052a7f8 30