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.

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.