Creating Interdependent Classes in C
This question explores how to create two C classes that each contain an object of the other class type. However, this direct approach leads to an error due to circular references.
Direct Implementation
Consider the following header files, which attempt to define two classes, foo and bar, each with a protected member of the other class type:
// bar.h #include "foo.h" class bar { foo f; }; // foo.h #include "bar.h" class foo { bar b; };
Compiling this code results in an error, as both headers include each other and create a circular reference.
Workaround: Forward Declarations and Pointers
To break this reference cycle, we can use forward declarations and pointers. Forward declarations allow us to declare the existence of a class without defining its members.
The modified header files are:
// bar.h class foo; // Forward declaration of foo class bar { foo* f; }; // foo.h class bar; // Forward declaration of bar class foo { bar* b; };
With these forward declarations, the headers can include each other without creating a circular reference. The actual definition of the class members is then placed in the corresponding .cpp files, where the necessary headers are included.
Using Pointers
To use the classes with pointers, we create instances of foo and bar with pointers to each other:
// main.cpp #include "foo.h" #include "bar.h" int main() { foo myFoo; bar myBar; myFoo.f = &myBar; // Assign the address of myBar to myFoo's f myBar.b = &myFoo; // Assign the address of myFoo to myBar's b }
This workaround allows us to create classes with interdependent objects using pointers, breaking the reference cycle and creating a valid program.
The above is the detailed content of How to Create Interdependent C Classes Without Circular References?. For more information, please follow other related articles on the PHP Chinese website!