简体   繁体   English

C ++声明

[英]C++ Declarations

I have a class, 'Cat', and a subclass of the Cat class, 'DerivedCat'. 我有一个“猫”类,以及一个猫类“ DerivedCat”的子类。 Cat has a function meow(), while DerivedCat overrides this function. Cat具有函数meow(),而DerivedCat会覆盖此函数。

In an application, I declare a Cat object: 在一个应用程序中,我声明一个Cat对象:

Cat* cat;

Later in the application, I initialize the Cat instance: 在应用程序的后面,我初始化Cat实例:

cat = new DerivedCat();
  1. Which 'meow()' gets called? 哪个'meow()'被调用? Why? 为什么?
  2. What are the advantages of declaring as the superclass type like this? 像这样声明为超类类型有什么好处?
  3. What is an example of where I would want to do this? 我想在哪里做这件事的一个例子是什么?

Assuming you meant Cat * cat; 假设您的意思是Cat * cat; , it depends on whether the meow method is virtual or not: ,取决于meow方法是否为虚拟方法:

  • If it is virtual, the definition in DerivedCat will be used. 如果是虚拟的,则将使用DerivedCat的定义。
  • If it is not virtual, the implementation in Cat will be used. 如果不是虚拟的,则将使用Cat的实现。

In Java all non static methods are virtual by default. 在Java中,默认情况下,所有非静态方法都是虚拟的。 This is often what you want. 这通常是您想要的。 However virtual methods can add a performance overhead at runtime to determine which implementation to call (eg a lookup in a vtable ). 但是,虚拟方法可能会在运行时增加性能开销,以确定要调用的实现(例如,在vtable中的查找)。 Even if you never create a subclass you may still have to pay for this performance overhead. 即使您从未创建子类,也可能仍要为此性能开销付费。 One of C++'s goals is to produce high performance code and therefore all methods are non-virtual by default. C ++的目标之一是生成高性能代码,因此默认情况下所有方法都是非虚拟的。

cat in your code is not a pointer or a reference, thus cat = new DerivedCat(); 您代码中的cat不是指针或引用,因此cat = new DerivedCat(); calls Cat::operator=(DerivedCat*) on cat . cat上调用Cat::operator=(DerivedCat*)

For this reason cat.meow() will call Cat::meow . 因此, cat.meow()将调用Cat::meow

EDIT after OP's comment: OP评论后编辑

If cat was a pointer or a reference, you could make it point to your DerivedCat instance. 如果cat是指针或引用,则可以使其指向DerivedCat实例。 In this case if you call a virtual Cat function that DerivedCat overloads, the version supplied by DerivedCat is called. 在这种情况下,如果你调用一个虚拟 Cat该功能DerivedCat重载,通过提供的版本DerivedCat被调用。

Polymorphism (which is this features you're asked about) is an important thing, it's at the base of Object Oriented Paradigm. 多态(这是您要问的功能)很重要,它是面向对象范例的基础。 It's not so easy to explain it with an example, I'd suggest you to read about it on Wikipedia or on C++Faq for more implementation details. 用一个例子来解释它不是那么容易,我建议您在WikipediaC ++ Faq上阅读它,以获得更多的实现细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM