继承是面向对象设计中非常重要的概念,在C++中尤为重要,C++中的继承比其它语言要更为复杂。
继承的好处
通过继承可以让子类拥有父类的所有成员变量以及函数,从而达到重用代码的目的。
关系描述:
继承代表 is a 的关系。比如:猫是动物

#include <iostream>//Animalclass Animal {public:int m_id;void walking(){std::cout << "Animal 在走 " << std::endl;}void run(){std::cout << "Animal 在🏃🏃🏃🏃🏃🏃 " << std::endl;}};// Cat类class Cat : public Animal{public:int m_weight;int m_height;void walking(){std::cout << "Cat 在走 " << std::endl;}void run(){std::cout << "Cat 在🏃🏃🏃🏃🏃🏃 " << std::endl;}};int main(int argc, const char * argv[]) {Cat cat;cat.m_id = 10; //访问父类的成员变量cat.m_weight = 20;cat.m_height = 30;cat.run();return 0;}
不像其它语言中的继承关系,C++中的类默认是没有继承其它基类的。而像Java、Object-C是有默认继承基类的。
Java里面定义一个类,默认是继承Object。
public class Animal { //默认是继承Object的}public class Cat extends Animal {}
iOS中的Object-C中定义一个类默认是继承NSObject类。
@interface Animal //默认是继承NSObject类@end@interface Cat : Animal@end
继承情况下,对象的内存是如何排布的
考虑下面的代码,whiteCat的成员变量(m_id、m_weight、m_height),内存中谁排在前面,谁排在后面?
#include <iostream>//Animalclass Animal {public:int m_id;};// Cat类class Cat : public Animal{public:int m_weight;};//白猫class WhiteCat: public Cat {public:int m_height;};int main(int argc, const char * argv[]) {WhiteCat *whiteCat = new WhiteCat();whiteCat->m_weight = 20; //访问父类的成员变量whiteCat->m_height = 30;whiteCat->m_id = 10;std::cout << &(whiteCat->m_id) << std::endl; //0x10052a7f0std::cout << &(whiteCat->m_weight) << std::endl; //0x10052a7f4std::cout << &(whiteCat->m_height) << std::endl; //0x10052a7f8return 0;}
结论:父类的成员变量在内存中会排在前面,子类的排在后面。
| 对象 | 成员变量 | 内存地址 | 内存数据 |
|---|---|---|---|
| &whiteCat | &(whiteCat->m_id) | 0x10052a7f0 | 10 |
| &(whiteCat->m_weight) | 0x10052a7f4 | 20 | |
| &(whiteCat->m_height) | 0x10052a7f8 | 30 | |
