c++的前向声明,里面有一个列表

forward declaration on c++ with a list inside

本文关键字:有一个 列表 声明 c++      更新时间:2023-10-16

我有两个类PetPerson

Here is the 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_;,但当我试图调用列表函数总是有一个链接问题。我的问题是如何在包含来自另一个类的对象的类中包含列表。

标准要求,除非有明确说明,否则在库模板中使用完整类型。这基本上抑制了您的设计(其中每个对象通过的值维护另一个类型的列表)。

你可以使用[smart]指针(指向容器的指针或指针的容器)来解决这个问题。

相关文章: