为什么我必须显式定义继承class提供的方法?
Why do I have to explicitly define a method provided by an inhereted class?
考虑以下几点:
#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 正确指出的那样:
It's probably worth pointing out that the "fix" isn't a fix at all. Any call to sparrow::speak()
will cause infinite recursion. It would need to be std::string speak() { return Bird::speak(); }
.
考虑以下几点:
#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 正确指出的那样:
It's probably worth pointing out that the "fix" isn't a fix at all. Any call to
sparrow::speak()
will cause infinite recursion. It would need to bestd::string speak() { return Bird::speak(); }
.