问题描述
有人可以解释以下代码的输出吗?
Can anyone explain the output of the following code?
#include <iostream>
#include <string>
class Animal
{
public:
Animal(const std::string & name) : _name(name) { }
~Animal() { }
virtual void printMessage() const
{
std::cout << "Hello, I'm " << _name << std::endl;
}
private:
std::string _name;
// other operators and stuff
};
class Cow : public Animal
{
public:
Cow(const std::string & name) : Animal(name) { }
~Cow() { }
virtual void printMessage()
{
Animal::printMessage();
std::cout << "and moo " << std::endl;
}
};
int main() {
Cow cow("bill");
Animal * animal = &cow;
cow.printMessage();
animal->printMessage();
}
输出
你好,我是账单
和moo
你好,我是账单
我不明白为什么。指针动物指向Cow类型的对象。 printMessage是一个虚函数。为什么Cow类的实现不是被调用的?
I don't understand why. The pointer animal points at an object of type Cow. printMessage is a virtual function. Why isn't the implementation of the Cow class the one that is called?
推荐答案
Cow
未覆盖 Animal
中的虚函数,因为它具有不同的签名。实际发生的是 Cow
隐藏 Animal
中的函数。
Cow
isn't overriding the virtual function from Animal
because it has a different signature. What's actually happening is that Cow
is hiding the function in Animal
.
结果是在 Animal
上调用 printMessage
只会使用 Animal
中的版本,无论 Cow
中的版本(它没有覆盖它),但是调用它来自 Cow
将使用 Cow
中的那个(因为它隐藏了 Animal
)。
The result of this is that calling printMessage
on an Animal
will just use the version in Animal
, regardless of the one in Cow
(it isn't overriding it), but calling it from Cow
will use the one in Cow
(because it hides the one from Animal
).
要解决此问题,请删除 Animal中的
,或在 const
Cow
中添加 const
。
To fix this, remove the const
in Animal
, or add the const
in Cow
.
在C ++ 2011中,您将能够使用覆盖
关键字来避免这样的微妙陷阱:
In C++ 2011, you will be able to use the override
keyword to avoid subtle traps like this:
class Cow : public Animal
{
public:
Cow(const std::string & name) : Animal(name) { }
~Cow() { }
virtual void printMessage() override
{
Animal::printMessage();
std::cout << "and moo " << std::endl;
}
};
请注意<$ c后添加的覆盖
$ C> printMessage()。如果 printMessage
实际上没有覆盖基类版本,这将导致编译器发出错误。在这种情况下,您将收到错误。
Notice the added override
after printMessage()
. This will cause the compiler to emit an error if printMessage
doesn't actually override a base class version. In this case, you would get the error.
这篇关于虚函数,它是基类中的const而不是派生的const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!