跟进this question,人们建议我选择“选项3”,这可能是这样的:
class b2Body {
private:
b2Body() {}
friend class b2World;
};
class Body : public b2Body {
private:
Body() {}
friend class World;
};
class b2World {
public:
b2Body *CreateBody() {
return new b2Body;
}
};
class World : public b2World {
public:
Body *CreateBody() {
return new Body;
}
};
int main() {
World w;
Body *b = w.CreateBody();
return 0;
}
但这有两个主要问题:
答案 0 :(得分:2)
只有b2World
可以创建b2Body
,所以这不会去任何地方。这些类显然不是为了继承,所以是的,而是聚合它们。
class Body {
public:
Body( b2Body* b ) : b2b( b ) {}
private:
b2Body*const b2b;
};
class World {
public:
World() : b2w( /* create b2w here */ ) {}
Body *CreateBody() {
return new Body( b2w->CreateBody( /*...*/ ); }
}
private:
b2World*const b2w;
};