简体   繁体   中英

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 . 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 . 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

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

in container.cpp

#include "item.h"

in item.h

class container; // do not include container.h

in 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 .

#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. 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".

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