zl程序教程

您现在的位置是:首页 >  后端

当前栏目

EasyC++75,继承(二)

C++继承 Easy 75
2023-06-13 09:11:31 时间

作者 | 梁唐

大家好,我是梁唐。

这是EasyC++系列的第75篇,来聊聊面向对象继承。

继承(二)

在实际编程当中,父类和子类之间会存在一些特殊的关键。

比如子类可以使用父类所有的public方法,我们来看一下之前的例子:

class Human {
   private:
     string _name;
     int _hp;
     int _property;
    public:
     Human(const string & name = "", const int hp = 100, const int property = 0): _name(name), _hp(hp), _property(property) {}
     void Name() const {
            return _name;
        }
     void work(int salary) {
            _property += salary;
        }
};

class Hero : public Human {
  private:
     string _super_power;
    public:
     Hero(const string &name = "", const int hp = 100, const property = 0, const string & sp): Human(name, hp, property), _super_power(sp) {}
     string SuperPower() const {
            return _super_power;
        }
     void use_power() {
            cout << _super_power << endl;
        }
};

Hero hero("peter", 100, 0, "spider");
hero.Name();

在这个例子当中Name是父类Human当中定义的,但对于子类的对象来说,它一样有权限可以使用。

除此之外还有两个特殊的关系,首先是父类的指针可以不进行显式类型转换的情况下指向子类对象:

Hero spider("peter", 100, 100, "spider");
Human *h = &spider;

同样,父类引用也可以在不进行强制类型转换的情况下引用子类对象:

Human &sp = spider;

一般来说C++会要求引用和指针与实际获得的类型匹配,但对于继承类来说是一个例外。不过这种例外是单向的,也就是说我们只能用父类指针或引用去接收子类对象,反过来是不行的。

除了赋值的时候更加方便之外,我们在传参的时候也会更加方便。我们在接收函数的参数设置成父类,那么无论是父类还是子类的实例都可以传入。

void show(Human &h) {
    ...
}