答案是:子类不一定要实现基类的虚函数。但如果没实现,他只能继续作为其他类的基类,而不能被实例化。
以下是编写的一个验证的小例子:
#include <iostream>
#include <string>
using namespace std;
class Animal {
public :
string type;
string sound;
Animal(string t, string s) : type(t), sound(s) {
cout << "Do Animal's constrcutor << " << endl;
}
virtual void yell(int sound) = 0;
};
class Dog : public Animal {
public :
Dog(string x, string y) : Animal(x, y){}
};
int main() {
Dog("小狗", "汪汪");//这条语句报错
return 0;
}
编译后会出现以下错误:

文章解释了在C++中,子类不一定要实现基类的虚函数,但若未实现,该子类将无法被实例化,如Dog类继承自Animal类时,未实现虚函数yell导致编译错误。

1329

被折叠的 条评论
为什么被折叠?



