这涉及一些非常棘手的继承,但请耐心等待。我的问题不是一个具体的错误,而只是“我将如何具体做到这一点?”
这个想法是有一个抽象的基类 Food (请注意,这对于问题来说都过于简单了)
//parent of Animal
//parent of Plant
//~Food()
//Food()
#pragma once
class Food
{
public:
Food(){}
~Food(){}
};
由此产生类动物和植物。我现在不太担心植物 动物需要有虚拟功能 Hunt and Eat
#pragma once
#include "Food.h"
class Animal : public Food
{
//eat() which accepts a Food* type as an argument. it is an abstract virtual in this class, it has the form
//bool eat(Food* food)
//hunt() which accepts an stl list of Food* pointers to Food type objects. the food list is declared globally in main and passed here. it has the form
//hunt(list<Food*> &foodlist)
};
由此产生更多的课程;Herbivore, Carnivore, Omnivore(继承自肉食动物和草食动物)。这是草食动物
//Child of Animal
//Parent of Lemur, Koala, Squirrel, Omnivore
//~Herbivore()
//hunt(list<Food*&foodList):bool (only eats plant types)
#pragma once
#include "Animal.h"
#include <iostream>
#include <string>
#include <list>
using namespace std;
class Herbivore : public virtual Animal
{
public:
Herbivore() {}
~Herbivore(){}
//eat() and hunt() are probably virtual here as well, as they aren't used directly, only the lower classes directly access them
};
从那些是最底层的子类,它们都大致具有这种形式。这是松鼠
//child of Herbivore
//leaf node
#pragma once
#include "Animal.h"
#include "Herbivore.h"
class Squirrel : public Herbivore
{
//bool eat() is fully defined here instead of being virtual.
//bool hunt() is fully defined here instead of being a virtual.
//both have the same argument lists as the virtuals in Animal
};
这是主要的
list<Food*> Food_list; //global list of Food items that will be passed to hunt()
int main()
{
list<Food*>::iterator it = Food_list.begin();
(*it)->eat(*it); //passing the iterator to itself as a test. this seems to work ok
(*it)->hunt(Food_list); //however this, in my code, refuses to work for a few reasons
};
所以基本上一切都从食物继承......但这是一件坏事。
我已经尝试了以下几个问题
我尝试了Animal中虚拟功能的初始版本,食物中没有,它抱怨食物没有功能狩猎
error C2039: 'hunt' : is not a member of 'Food'
....我想这是公平的,虽然它不应该看松鼠而不是食物类吗?
我尝试在 Food 中创建一个纯虚拟来吃和打猎,从那时起,每次尝试实例化任何类型的叶子类(如松鼠或老虎或其他)都会返回“无法实例化抽象类”错误。
error C2259: 'Squirrel' : cannot instantiate abstract class
我试着让食物中的吃和狩猎不那么抽象,比如狩猎(列表和食物列表),但是它说“语法错误,标识符'列表'”,就像它不知道列表是什么......即使在我之后包含在 Food.h 中
error C2061: syntax error : identifier 'list'
并且所有这些错误都与错误“'Food::hunt': function does not take 1 arguments”配对
error C2660: 'Food::hunt' : function does not take 1 arguments
我的总体问题是,您如何将这个抽象虚函数从 Animal 转换为它的叶类?你会怎么称呼它?基本上我所尝试的一切都惨遭失败 *不要担心eat()或hunt()里面有什么,我只是在寻找正确的声明*
这个项目的 github 也可以在这里 https://github.com/joekitch/OOP_JK_Assignment_4 如果需要的话