Declare an object even before that class is created

前端 未结 5 624
没有蜡笔的小新
没有蜡笔的小新 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: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.

提交回复
热议问题