简体   繁体   中英

C++ Class Object inside another class

It keeps me getting this error in Event.h :

field 'group' has incomplete type 'Group'

For context, I want to have a class Group which has an owner (from class Person ) and it consists of a vector of people (class Person ):

Group.h

class Person;
#include "Person.h"

Class Group
{
    private:
        std::string name;
        std::vector<Person> people;
        int size = 0;
        Person owner;
    public:
        Group(Person owner);
        ~Group();
}

In the Person class, I want to have just a vector of lists (class List, not important for this specific error). Note that in the Person class I have a constructor Person(int id);

In the Event class, I want to have a group of people invited that can be saved as a Group class:

Event.h

class Group;
#include "Group.h"

class Event
{
    private:
        std::string tittle;
        std::string description;
        bool locked;
        bool checked;
        Group group;

    public:
        Event(std::string tittle);
        ~Event();
}

Why can't I have a Person owner on my group?

You are defining something out of order. Perhaps the #ifdef guards.

This compiles just fine:


class Person {};

class Group
{
    private:
        std::string name;
        std::vector<Person> people;
        int size = 0;
        Person owner;
    public:
        Group( Person owr );
        ~Group();
};

class Event
{
    private:
        std::string tittle;
        std::string description;
        bool locked;
        bool checked;
        Group group;

    public:
        Event(std::string tittle);
        ~Event();
};

Godbolt: https://godbolt.org/z/f785vK1dq

The following works fine for me ( Online Demo ):

Person.h

#ifndef Person_H
#define Person_H

class Person
{
};

#endif

Group.h

#ifndef Group_H
#define Group_H

#include "Person.h"
#include <string>
#include <vector>

class Group
{
    private:
        std::string name;
        std::vector<Person> people;
        int size = 0;
        Person owner;
    public:
        Group(Person owner) : owner(owner) {}
};

#endif

Event.h

#ifndef Event_H
#define Event_H

#include "Group.h"
#include <string>

class Event
{
    private:
        std::string tittle;
        std::string description;
        bool locked = false;
        bool checked = false;
        Group group;

    public:
        Event(std::string tittle) : tittle(tittle), group(Person{}) {}
};

#endif

main.cpp

#include <iostream>
#include "Event.h"

int main()
{
    Event evt("title");
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM