誰でも次のコードの出力を説明できますか?基本クラスではconstで、派生クラスではconstではない仮想関数
#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クラスの実装が呼び出されるのはなぜですか?
+1完全で最小限の作業例 – Flexo
Cowクラスの関数を 'virtual void printMessage()const'に変更しようとしましたか? –