空门仓wlp 2020-04-09 20:00 采纳率: 0%
浏览 234

c++一道英文题,消除两个类构造的顺序依赖性

Define two classes, each with a static member, so that the construction of each static member involves a referece to the other. Where might such constructors appear in real code? How can these classes be modifiered to eliminate the order dependence in the constructors?

以上是原题,这话的中文意思懂,但不理解是个什么情况,网上也搜不着,
拜托大佬们指点下了。

  • 写回答

2条回答 默认 最新

  • qtchen_1988 2020-04-10 18:47
    关注
    #include <iostream>
    
    using namespace std;
    
    class B;
    class A
    {
    public:
        A();
        void print(){printf("this A print");}
    private:
        static B b;
    };
    class B
    {
    public:
        B();
        void print(){printf("this B print");}
    private:
        static A a;
    };
    
    //对调上下顺序,修改AB构造函数先后顺序
    A B::a = A();
    B A::b = B();
    
    A::A()
    {
        printf("this A constructed: ");
        b.print();
        printf("\n");
    }
    
    B::B()
    {
        printf("this B constructed: ");
        a.print();
        printf("\n");
    }
    
    int main()
    {
        return 0;
    }
    

    不知是否你要的结果

    评论

报告相同问题?