为什么我必须明确定义由固有类提供的方法?

Car*_*bon 0 c++ inheritance diamond-problem

考虑以下:

#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();
}
Run Code Online (Sandbox Code Playgroud)

编译它,你会得到:

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'
Run Code Online (Sandbox Code Playgroud)

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

Que*_*tin 5

因为,与您标记的不同,您没有钻石继承.你sparrow是两个animal人,其中只有一个是混凝土的bird.继承的另一个landAnimal不是.

获得实际钻石所需要的是虚拟继承,但是你会发现它带有一系列警告.

另一方面,Martin Bonner正确地指出:

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