谁能解释以下代码的输出?
#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();
}
输出是
你好,我是比尔
和哞
你好,我是比尔
我不明白为什么。指针 Animal 指向 Cow 类型的对象。 printMessage 是一个虚函数。为什么调用的不是 Cow 类的实现?
Cow
没有覆盖虚函数Animal
因为它有不同的签名。实际发生的事情是这样的Cow
is hiding中的函数Animal
.
这样做的结果是调用printMessage
on an Animal
将仅使用中的版本Animal
,无论其中的一项Cow
(它并没有覆盖它),但是从Cow
将使用其中的一个Cow
(因为它隐藏了一个Animal
).
要解决此问题,请删除const
in Animal
,或添加const
in Cow
.
在 C++ 2011 中,您将能够使用override
关键字以避免像这样的微妙陷阱:
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;
}
};
注意添加的override
after printMessage()
。如果出现以下情况,这将导致编译器发出错误printMessage
实际上并没有覆盖基类版本。在这种情况下,您会收到错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)