简体   繁体   中英

C++ creating doubly-linked classes

I have two classes which both need to have links to objects of one another. Here's some example code to show my issue:

//object1.h
class object1{
    object2 *pointer;
}

My other class:

//object2.h
class object2{
    object1 *pointer;
}

I'm not exactly sure how I'm supposed include the two classes simultaneously in each other's file. Having an include for the other class in both files is causing me issues. Preferably, I would like to just have both the objects in one file, since their headers are only a few lines of code each, but this causes an error on whichever class is first declared in the file, since the other class header isn't preceeding it; It gives me an invalid type error.

Use a forward declaration :

//object1.h
class object2;
class object1{
    object2 *pointer;
};

//object2.h
class object1;
class object2{
    object1 *pointer;
};

A forward declaration introduces an incomplete type . In short, it tells the compiler that the definition exists somewhere else. You have some limitations with incomplete types, though. Since the compiler doesn't know its full definition, it cannot do things like allocating enough space for it, invoking member functions, checking the virtual table, etc. Fundamentally, what you can do is to just declare references/pointers to them and pass'em around:

// Forward declaration
class X;

class Y {
private:
//  X x;    // Error: compiler can't figure out its size
    X &x;    // A reference is ok
public:
    Y(X &x) : x(x) { }

//  void foo() { x.foo(); } // Error: compiler can't invoke X's member
    void bar();
};

// Full declaration
class X {
public:
    void foo() { }
};

void Y::bar()
{
    x.foo(); // Now it is OK to invoke X's member
}

A good pattern is to use forward declarations to break dependency cycles between headers or class definitions and make you wonder whatever your design could be improved.

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