我有两个类(class) Pet
和 Person
这是 Person.h:
#ifndef PERSON_H
#define PERSON_H
#include <list>
class Pet;
class Person
{
public:
Person();
Person(const char* name);
Person(const Person& orig);
virtual ~Person();
bool adopt(Pet& newPet);
void feedPets();
private:
char* name_;
std::list<Pet> pets_;
};
#endif
这是 Pet.h
#ifndef PET_H
#define PET_H
#include <list>
#include "Animal.h"
class Person;
class Pet : public Animal
{
public:
Pet();
Pet(const Pet& orig);
virtual ~Pet();
std::list<Pet> multiply(Pet& pet);
private:
std::string name_;
Person* owner_;
};
#endif
我遇到的问题是:
/usr/lib/gcc/i686-pc-cygwin/3.4.4/include/c++/bits/list.tcc:129: error: invalid use of undefined type `struct Pet'
Person.h:13: error: forward declaration of `struct Pet'
我修复了尝试把这个 std::list<Pet>* pets_;
但是当我尝试调用列表函数时总是有链接问题。我的问题是如何必须在包含来自另一个类的对象的类中包含一个列表。
最佳答案
该标准要求,除非明确说明,否则您必须将完整类型与库模板一起使用。这基本上会阻碍您的设计(其中每个对象都按值维护另一种类型的列表)。
您可以使用 [智能] 指针(指向容器的指针或指针的容器)来解决此问题。
关于c++ - c++ 上的前向声明,里面有一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15883302/