多态性测试不起作用

0 c++ polymorphism

以下代码无法编译,但我无法理解错误:

#include <iostream>

class FamilyMember {

    int age;
    public:
    virtual int myage () = 0;
};


class Grandfather: public FamilyMember {

    int age;
    public:
    Grandfather (): age(60) {
        std::cout << "Im grandpa" << std::endl;
    }
    ~Grandfather () {
        std::cout << "Oh no! Grandpa is dead!" << std::endl;
    }
    virtual int myage () const {
        return age;
    }
};


class Father: public Grandfather {

    int age;
    public:
    Father (): age(40) {
        std::cout << "Im papa" << std::endl;
    }
    ~Father () {
        std::cout << "Papa is gone, noooooo!" << std::endl;
    }
    virtual int myage () const {
        return age;
    }
};


class Son: public Father {

    int age;
    public:
    Son (): age(20) {
        std::cout << "Im the kid" << std::endl;
    }
    ~Son () {
        std::cout << "Son is dead? He was so young!" << std::endl;
    }
    int myage () const {
        return age;
    }
};

int main () {

    Grandfather G;
    Father F;
    Son S;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

以下是我得到的错误(我将代码减少到打破它的最小量,因此行号不匹配).

main.cc:535: error: cannot declare variable ‘G’ to be of abstract type ‘Grandfather’
main.cc:161: note:   because the following virtual functions are pure within ‘Grandfather’:
main.cc:157: note:  virtual int FamilyMember::myage()
main.cc:536: error: cannot declare variable ‘F’ to be of abstract type ‘Father’
main.cc:177: note:   because the following virtual functions are pure within ‘Father’:
main.cc:157: note:  virtual int FamilyMember::myage()
main.cc:537: error: cannot declare variable ‘S’ to be of abstract type ‘Son’
main.cc:193: note:   because the following virtual functions are pure within ‘Son’:
main.cc:157: note:  virtual int FamilyMember::myage()
make: *** [main.o] Error 1
Compilation failed.
Run Code Online (Sandbox Code Playgroud)

For*_*veR 6

不同的签名.

virtual int myage () = 0;
Run Code Online (Sandbox Code Playgroud)

在儿童班.

virtual int myage () const
Run Code Online (Sandbox Code Playgroud)

制作pure-virtual myage const,或non-const在孩子中使这个功能.