C++在作为超类传递后使用overriden方法
C++ Using an overriden method after passing as superclass
如果我有一个C++函数/方法,例如:
getSound(Animal a){
a.printSound();
}
然后给它传递一个Dog
对象,该对象扩展了类Animal
,但覆盖了Animal的printSound()
方法,有没有办法在getSound()
中使用Dog的printSound()
?
我已经尝试在Animal
类定义中使printSound()
成为虚拟的,但我仍然得到原始printSound()
的输出。
提前谢谢。
这是因为对象切片,因为您按值接受参数。
通过引用接受为:
void getSound(Animal & a); //now reference
如果Animal::printSound()
没有更改对象的状态,则使其成为const
成员函数(如果它还不是常量),然后接受const
引用的参数为:
void getSound(Animal const & a); //now const reference
使printSound
虚拟化是正确的。将getSound
的签名更改为Animal&
或const Animal&
。通过按值取一个Animal
,您就从您的Dog
构造了一个新的Animal
,而这只是Animal
,而不是Dog
。
当您调用getSound
时,您正在按值传递Animal
。这意味着通过调用Animal
的复制构造函数来生成Dog
的副本。Animal
的复制构造函数构造的是Animal
,而不是Dog
。你可能想要通过参考:
getSound(Animal& a){
a.printSound();
}
除了一件事之外,您基本上都做对了。
通过引用传递动物对象
getSound(Animal &a);
或者提供一个指向有问题对象的指针。
getSound(Animal *a) {
a->printSound(); //Mind the -> in this case.
}
要调用这个函数,你可以这样做:
Dog D;
getSound(&D); //Passes a pointer to the function.
否则,您将构造一个"Animal"类型的新对象,而不是真正"传递"一只狗。
实际上,最好使用指针解决方案,否则在传递派生对象时会遇到问题,因为它将期望Animal
类型的对象,而不会满足于其他任何对象。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- 访问C 中的Overriden Parent虚拟方法
- C 方法指向Overriden方法
- 从另一种基本方法调用Overriden方法
- C++在作为超类传递后使用overriden方法
- 在C++中将overriden类方法作为链调用
- 使用std::thread从派生类中调用overriden方法