c++

类方法在C++中的继承与多态应用

小樊
83
2024-08-27 13:40:26
栏目: 编程语言

在C++中,类方法的继承和多态主要通过基类(父类)和派生类(子类)之间的关系来实现

  1. 继承:

继承是面向对象编程的一个重要特性,它允许一个类(派生类)继承另一个类(基类)的属性和方法。这样,派生类可以重用基类的代码,同时还可以添加或覆盖基类的方法。

#include<iostream>

class Base {
public:
    void print() {
        std::cout << "Base class method"<< std::endl;
    }
};

class Derived : public Base {
public:
    void print() {
        std::cout << "Derived class method"<< std::endl;
    }
};

int main() {
    Base *base = new Base();
    base->print(); // 输出 "Base class method"

    Derived *derived = new Derived();
    derived->print(); // 输出 "Derived class method"

    Base *base_ptr = new Derived();
    base_ptr->print(); // 输出 "Base class method",因为print()方法不是虚函数

    delete base;
    delete derived;
    delete base_ptr;

    return 0;
}
  1. 多态:

多态是指允许使用基类指针或引用来操作派生类对象。为了实现多态,我们需要将基类的方法声明为虚函数(virtual)。这样,当通过基类指针或引用调用该方法时,会根据实际对象的类型来调用相应的方法。

#include<iostream>

class Base {
public:
    virtual void print() {
        std::cout << "Base class method"<< std::endl;
    }
};

class Derived : public Base {
public:
    void print() override {
        std::cout << "Derived class method"<< std::endl;
    }
};

int main() {
    Base *base = new Base();
    base->print(); // 输出 "Base class method"

    Derived *derived = new Derived();
    derived->print(); // 输出 "Derived class method"

    Base *base_ptr = new Derived();
    base_ptr->print(); // 输出 "Derived class method",因为print()方法是虚函数

    delete base;
    delete derived;
    delete base_ptr;

    return 0;
}

在这个例子中,我们将Base类的print()方法声明为虚函数。当我们通过Base类指针调用print()方法时,如果实际对象是Derived类的实例,那么将调用Derived类的print()方法。这就是多态的体现。

0
看了该问题的人还看了