为什么我必须显式定义一个由固有类提供的方法
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正确指出的那样:
可能值得指出的是,"修复"根本不是修复。对
sparrow::speak()
的任何调用都将导致无限递归。它需要是std::string speak() { return Bird::speak(); }
。
相关文章:
- 不能将方法返回的值用于另一个方法
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- 我在C++中编写了一个方法来打印树类的预序,但它显示了分割错误
- 重写另一个方法 [C++] 使用的超类回调函数
- C++:如何使用传递引用在一个方法中返回多个值
- 为什么一个方法对同一个变量有常量和非常量参数?
- 从同一类中的另一个方法调用方法时出错
- 向现有类添加一个方法以逐行读取文件的内容
- 无法从派生的一个方法调用基类方法
- 如何将一个方法中的值返回到同一类的另一个方法
- 方法重载 C++ -> 只有一个方法调用
- 在另一个线程中执行一个方法
- 是否可以在另一个方法中使用模板类中定义的虚拟方法
- 调用方法,该方法修改字段,而使用该字段的另一个方法正在执行
- 将一个方法作为参数传递给另一个方法,该方法本身将传递的方法传递给 std 线程
- 仅专用于模板类的一个方法(部分)
- 确定一个方法是否是纯虚拟的(c++)
- 是否可以判断一个方法在编译时是否可以公开访问
- 我正在尝试创建一个方法,该方法使用指针算术返回一对,它是否会出错
- 从 ndk 中的 jni 方法调用另一个C++方法