简体   繁体   中英

C++ many classes referencing each other

I have a series of classes that need to reference each other like this

class A
{
     vector<B *> B_list;
     vector<C *> C_list;
     ... 
};

for each class. I'm currently using one header file for all.cpp files which looks like this:

class B; class C; class A {...}; class B {...}; class C{...};

I'm wondering if there's a way to have one header per class.

Edit for clarity: I'm starting a project and need three pretty large, detailed, and distinct classes that each interact with each other frequently.

I have created minimal code for each class like this class A { C *c_item; B *b_item; } A; class A { C *c_item; B *b_item; } A; that includes the other classes and each header hass a blank.cpp file. Compiling it results in undefined type errors because no class can be defined without the others.

So, I added in forward declarations to each class header like class C; class B; class C; class B; which results in 'C' does not name a type errors and in my original code, I got a few class already defined errors when I was messing around with forward declarations.

The only way I could get everything working was to use one header file like I said above. I then tried using three separate headers that all included one header with forward declarations class A; class B; class C; class A; class B; class C; and that didn't fix anything.

Edit 2, found the issue: I was writing class A {...} A; and now I'm writing class A {...}; with the forward declarations at the top of each file and it's working, but I'm not sure why that difference made it work.

Yes, you can have one header per class, for the class A header, type #include "classB.h" at the top and for the class B header type "include "classC.h" in that and then you should have 3 separate header files and the code you wrote should be fine.

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