以下代码无法编译,但我无法理解错误:
#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;
}
这是我得到的错误(我将代码减少到破坏它的最小数量,因此行号将不匹配)。
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.