Declare an object even before that class is created

前端 未结 5 623
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 14:03

Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the sec

相关标签:
5条回答
  • 2021-02-04 14:24

    You can't do something like this:

    class A {
        B b;
    };
    class B {
        A a;
    };
    

    The most obvious problem is the compiler doesn't know how to large it needs to make class A, because the size of B depends on the size of A!

    You can, however, do this:

    class B; // this is a "forward declaration"
    class A {
        B *b;
    };
    class B {
        A a;
    };
    

    Declaring class B as a forward declaration allows you to use pointers (and references) to that class without yet having the whole class definition.

    0 讨论(0)
  • 2021-02-04 14:33

    There's an elegant solution using templates.

    template< int T > class BaseTemplate {};
    typedef BaseTemplate< 0 > A;
    typedef BaseTemplate< 1 > B;
    // A
    template<> class BaseTemplate< 0 >
    {
    public:
       BaseTemplate() {} // A constructor
       B getB();
    }
    
    // B
    template<> class BaseTemplate< 1 >
    {
    public:
       BaseTemplate() {} // B constructor
       A getA();
    }
    
    inline B A::getB() { return A(); }
    inline A B::getA() { return B(); }
    

    This code will work! So, why does it work? The reason has to do with how templates are compiled. Templates delay the creation of function signatures until you actually use the template somewhere. This means that neither getA() nor getB() will have their signatures analyzed until after both classes A and B have already been fully declared. That's the magic of this method.

    0 讨论(0)
  • 2021-02-04 14:34

    You can't declare an instance of an undefined class but you can declare a pointer to one:

    class A;  // Declare that we have a class A without defining it yet.
    
    class B
    {
    public:
        A *itemA;
    };
    
    class A
    {
    public:
        B *itemB;
    };
    
    0 讨论(0)
  • 2021-02-04 14:35

    Is this close to what you want: The first class contains the second class, but the second class (that is to be created first) just has a reference to the first class?

    0 讨论(0)
  • 2021-02-04 14:38

    This is called cross reference. See here an example.

    0 讨论(0)
提交回复
热议问题