函数可以接受抽象基类作为参数吗

函数可以接受抽象基类作为参数吗

本文介绍了函数可以接受抽象基类作为参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在熟悉基本类和封装的概念后,我开始着手了解多态性,但我无法弄清楚如何使其工作.我搜索过的许多示例都确实是,真的 强制的(Foo 和 Bar 类太抽象了,我看不到实用程序),但这是我对基本概念的理解:你编写一个基类,从中派生出一大堆其他改变基本方法的东西(但不是它们是什么"),然后你可以编写通用函数来接受和处理任何派生类,因为您已经在某种程度上标准化了它们的外观.在这个前提下,我尝试实现基本的 Animal->cat/dog 层次结构,如下所示:

Having gotten comfortable with the idea of basic classes and encapsulation, I've launched myself towards understanding polymorphism, but I can't quite figure out how to make it work. Many of the examples I've searched through come across as really, really forced (classes Foo and Bar are just too abstract for me to see the utility), but here's how I understand the basic concept: you write a base class, derive a whole bunch of other things from it that change what the base methods do (but not what they "are"), then you can write general functions to accept and process any of the derived classes because you've somewhat standardized their appearance. With that premise, I've tried to implement the basic Animal->cat/dog hierarchy like so:

class Animal {
  public:
    virtual void speak() = 0;
};

class Dog : public Animal {
  public:
    void speak() {cout << "Bark bark!" << endl;}
};

class Cat : public Animal {
  public:
    void speak() {cout << "Meow!" << endl;}
};

void speakTo(Animal animal) {
    animal.speak();
}

speakTo 可以使用的地方可以使用一般类型的动物并让它说话.但据我了解,这不起作用,因为我无法实例化 Animal(特别是在函数参数中).那么,我问,我是否了解多态性的基本用途,以及我怎样才能真正做我已经尝试做的事情?

where speakTo can take can take a general kind of animal and make it, well, speak. But as I understand it, this doesn't work because I can't instantiate Animal (specifically in the function argument). I ask, then, do I understand the basic utility of polymorphism, and how can I really do what I've tried to do?

推荐答案

您不能将 Animal 对象传递给派生类函数,因为您无法创建 Animal 的对象类等等,它是一个抽象类.
如果一个类至少包含一个纯虚函数(speak()),那么这个类就变成了一个抽象类,你不能创建它的任何对象.但是,您可以创建指针或引用并将它们传递给它.您可以传递一个 Animal 指针或对该方法的引用.

You cannot pass an Animal object to the derived class function because you cannot create an object of Animal class et all, it is an Abstract class.
If an class contains atleast one pure virtual function(speak()) then the class becomes an Abstract class and you cannot create any objects of it. However, You can create pointers or references and pass them to it.You can pass an Animal pointer or reference to the method.

void speakTo(Animal* animal)
{
    animal->speak();
}

int main()
{
    Animal *ptr = new Dog();
    speakTo(ptr);

    delete ptr;   //Don't Forget to do this whenever you use new()
    return 0;
}

这篇关于函数可以接受抽象基类作为参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 13:15