C ++作为超类传递后使用overriden方法(C++ Using an overriden method after passing as superclass)

编程入门 行业动态 更新时间:2024-10-24 11:19:55
C ++作为超类传递后使用overriden方法(C++ Using an overriden method after passing as superclass)

如果我有一个C ++函数/方法,例如:

getSound(Animal a){ a.printSound(); }

然后传递一个Dog对象,它扩展了Animal类,但是覆盖了Animal的printSound()方法,有没有办法在getSound()中使用Dog的getSound() ?

我已经尝试在Animal类定义虚拟中创建printSound() ,但我仍然得到原始printSound()的输出。

提前致谢。

If I have a C++ function/method, for example:

getSound(Animal a){ a.printSound(); }

and then pass it a Dog object that extends the class Animal but overrides Animal's printSound() method, is there a way of using Dog's printSound() within getSound()?

I have tried making printSound() in the Animal class definition virtual, but I am still getting the output of the original printSound().

Thanks in advance.

最满意答案

使printSound虚拟是正确的。 更改getSound的签名以获取Animal&或const Animal& 。 通过以Animal为价值,你正在从你的Dog身上构建一个新的Animal ,这只是一个Animal ,而不是一只Dog 。

Making printSound virtual was correct. Change the signature of getSound to take a Animal& or const Animal&. By taking an Animal by value you are constructing a new Animal from your Dog, and that's just an Animal, not a Dog.

更多推荐

本文发布于:2023-08-07 18:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465536.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   overriden   method   superclass   passing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!