简体   繁体   English

两个类相互引用

[英]two classes referencing each other

Say there are two classes, which need each other: container and item . 假设有两个类,它们需要彼此: 容器项目 The class container creates instances of class item . 容器创建类项的实例。 Each instance of class item holds an instance of class container and needs to call only the method method_called_by_item of class container . 项的每个实例都包含一个类容器的实例,只需要调用类容器的方法method_called_by_item Class container needs to see all fields of class item . 容器需要查看类项的所有字段。

The problem is the forward declaration: I want to have a forward declaration inside of item.h , so that the class item can have a container as field and call the method method_called_by_item . 问题是前向声明:我想在item.h中有一个前向声明,这样类可以有一个容器作为字段并调用方法method_called_by_item How do I do that? 我怎么做?

Class container , which creates items. 容器 ,用于创建项目。

// container.h
#ifndef CONTAINER_H
#define CONTAINER_H

#include "item.h"

class container{

public:
  item * create_item();
  void method_called_by_item(item * i);
};

#endif //CONTAINER_H

The implementation: 实施:

// container.cpp
#include "container.h"

item * container::create_item(){
  return new item(this);
}

void container::method_called_by_item(item * i){
  // do stuff with item
}

The class item , which needs to call one method of container : ,需要调用一个容器方法:

// item.h
#ifndef ITEM_H
#define ITEM_H

#include <iostream>

class container;

class item{

public:
  item(container * c);
  void do_something();
  container * c;
};

#endif //ITEM_H

The implementation: 实施:

// item.cpp
#include "item.h"

item::item(container * c){
  this->c = c;
}
void item::do_something(){
  this->c->method_called_by_item(this);
}

in container.h 在container.h中

class item; // do not include the item.h

in container.cpp 在container.cpp中

#include "item.h"

in item.h 在item.h中

class container; // do not include container.h

in item.cpp 在item.cpp中

#include "container.h"

You have already added the forward declaration to item.h so all you need to do is add the following line to item.cpp . 您已经向item.h添加了前向声明,因此您需要做的就是将以下行添加到item.cpp中

#include "container.h"

container.h already includes item.h so you don't have to make any additional changes but as Mahmoud Fayez pointed out you can add a forward declaration there as well. container.h已经包含item.h所以您不必进行任何额外的变化,但作为马哈茂德·法耶兹指出,你可以有添加前向声明为好。 This will remove the dependency on the header file which is typically desired - it can reduce build times on large projects and allows the header file to "stand on it's own". 这将消除通常需要的头文件的依赖性 - 它可以减少大型项目的构建时间,并允许头文件“独立”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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