[英]C++ Class Object inside another class
It keeps me getting this error in Event.h
:它让我在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
):对于上下文,我想要一个 class Group
,它有一个所有者(来自 class Person
),它由一个人向量(类Person
)组成:
Group.h组.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).在Person
class 中,我只想有一个列表向量(List 类,对于这个特定错误并不重要)。 Note that in the Person
class I have a constructor Person(int id);
请注意,在Person
class 我有一个构造函数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
class 中,我想邀请一组可以保存为Group
class 的人:
Event.h事件.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?为什么我的群组中不能有Person
所有者?
You are defining something out of order.您正在定义一些乱序的东西。 Perhaps the #ifdef guards.也许#ifdef 守卫。
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神栓: https://godbolt.org/z/f785vK1dq
The following works fine for me ( Online Demo ):以下对我来说很好(在线演示):
Person.h人.h
#ifndef Person_H
#define Person_H
class Person
{
};
#endif
Group.h组.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事件.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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.