温馨提示×

C++中如何生成多态对象

c++
小樊
82
2024-08-30 00:57:08
栏目: 编程语言

在C++中,要生成多态对象,需要使用基类指针或引用来指向派生类对象。这样可以让我们通过基类接口调用派生类的实现,实现多态行为。

下面是一个简单的示例:

#include<iostream>

// 基类
class Animal {
public:
    virtual void makeSound() const {
        std::cout << "The animal makes a sound"<< std::endl;
    }
};

// 派生类1
class Dog : public Animal {
public:
    void makeSound() const override {
        std::cout << "The dog barks"<< std::endl;
    }
};

// 派生类2
class Cat : public Animal {
public:
    void makeSound() const override {
        std::cout << "The cat meows"<< std::endl;
    }
};

int main() {
    // 使用基类指针创建多态对象
    Animal* animal1 = new Dog();
    Animal* animal2 = new Cat();

    // 通过基类指针调用派生类的方法
    animal1->makeSound(); // 输出 "The dog barks"
    animal2->makeSound(); // 输出 "The cat meows"

    // 释放内存
    delete animal1;
    delete animal2;

    return 0;
}

在这个示例中,我们定义了一个基类Animal和两个派生类DogCat。基类中有一个虚函数makeSound(),派生类分别重写了这个函数。在main()函数中,我们使用基类指针Animal*创建了多态对象,并通过基类接口调用了派生类的实现。这就是C++中多态对象的创建和使用方式。

0