为什么我必须显式定义一个由固有类提供的方法

Why do I have to explicitly define a method provided by an inhereted class?

本文关键字:一个 方法 定义 为什么      更新时间:2023-10-16

考虑以下内容:

#include <string>
struct animal
{
public:
virtual std::string speak() = 0;
};
struct bird : public animal
{
public:
std::string speak()
{
return "SQUAK!";
}
};
struct landAnimal : public animal
{
virtual int feet() = 0;
};

struct sparrow : public bird, public landAnimal
{
int feet() { return 2; }
// This solves it, but why is it necessary, doesn't bird provide this?
// std::string speak(){ return this->speak(); } 
};
int main()
{
sparrow tweety = sparrow();
}

编译它,你会得到:

1>ex.cpp(35): error C2259: 'sparrow': cannot instantiate abstract class
1>  ex.cpp(35): note: due to following members:
1>  ex.cpp(35): note: 'std::string animal::speak(void)': is abstract
1>  ex.cpp(10): note: see declaration of 'animal::speak'

为什么需要注释的方法来编译它?

因为,与您标记的不同,您没有钻石继承。您的sparrow是两个animal,其中只有一个由bird具体化。另一个是通过landAnimal继承的,但不是。

获得一颗真正的钻石需要的是虚拟继承,但正如你所发现的,它附带了大量的注意事项。

顺便说一句,正如Martin Bonner正确指出的那样:

可能值得指出的是,"修复"根本不是修复。对sparrow::speak()的任何调用都将导致无限递归。它需要是std::string speak() { return Bird::speak(); }