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?
以上是原题,这话的中文意思懂,但不理解是个什么情况,网上也搜不着,
拜托大佬们指点下了。
#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;
}
不知是否你要的结果
class B;
class A
{
private:
static B b;
public:
A();
};
class B
{
private:
static A a;
public:
B()
{
a = A();
}
};
A::A() { b = B(); }
int main()
{
A a;
return 0;
}