以下是一个简单的例子,展示了类的继承用法:

#include <iostream>
using namespace std;

// 父类
class Animal {
public:
    void eat() {
        cout << 'Animal is eating.' << endl;
    }
};

// 子类
class Cat : public Animal {
public:
    void meow() {
        cout << 'Cat is meowing.' << endl;
    }
};

// 子类
class Dog : public Animal {
public:
    void bark() {
        cout << 'Dog is barking.' << endl;
    }
};

int main() {
    Cat cat;
    Dog dog;
    cat.eat(); // 继承自父类
    cat.meow();
    dog.eat(); // 继承自父类
    dog.bark();
    return 0;
}

在这个例子中,Animal 是一个父类,它有一个 eat() 方法。Cat 和 Dog 是两个子类,它们分别继承自 Animal,并分别有自己的 meow() 和 bark() 方法。在主函数中,我们创建了一个 Cat 对象和一个 Dog 对象,并调用了它们的方法,包括继承自父类的 eat() 方法。

C++ 类继承:编写多个类示例

原文地址: https://www.cveoy.top/t/topic/n7Ak 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录