Pregunta

i have Parent and Child classes. Child inherits from Parent. I want to store in a vector of Child objects the children of a parent object.

I include the Child header into the Parent header, but i have to include the Parent header into the Child header (since it inherits from Parent).

How do i overcome this circular inclusion?

Parent.h

#pragma once
#include <vector>
#include "Child.h"

using std::vector;
class Parent
{
public:
    Parent();
    ~Parent();
    vector<Child> children;
};

Parent.cpp

#include "stdafx.h"
#include "Parent.h"


Parent::Parent()
{   
}


Parent::~Parent()
{
}

Child.h

#pragma once
#include "Parent.h"
class Child : Parent
{
public:
    Child();
    ~Child();
};

Child.cpp

#include "stdafx.h"
#include "Child.h"


Child::Child()
{
}


Child::~Child()
{
}

Errors

child.h(4): error C2504: 'Parent' : base class undefined

parent.h(11): error C2065: 'Child' : undeclared identifier

¿Fue útil?

Solución

Forward declare Child, and store pointer inside of vector.

Parent.h

#pragma once
#include <vector>

using std::vector;
class Child;
class Parent
{
public:
    Parent();
    ~Parent();
    vector<Child*> children;
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top