无法从该对象继承?
跟进这个问题,人们有建议我选择“选项 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;
}
但是有两个主要问题this:
Body
永远无法被构造,即使使用World::CreateBody
(因为b2Body
是私有的)- 即使可以,那么
b2Body
部分无法正确初始化(b2World::CreateBody
需要被调用)
这是否意味着我永远不能从 b2Body< 继承/code>/
b2World
并遵循相同的设计模式? (请记住,我无法编辑 b2* 类)
如果是这样,我想你们会建议我只保留 b2World
和 b2Body
作为成员变量?
我认为现在归结为这两个选项:
Following up on this question, people have suggested I go with "option 3" which might look like this:
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;
}
But there are two major problems with this:
Body
can never be constructed, even withWorld::CreateBody
(becauseb2Body
is private)- Even if it could, then the
b2Body
part wouldn't be initialized correctly (b2World::CreateBody
needs to be called)
Does this mean I can never inherit from b2Body
/b2World
and follow this same design pattern? (keep in mind that I can't edit the b2* classes)
If so, I suppose you guys would recommend I just keep b2World
and b2Body
as member variables instead?
I think it comes down to these two options now:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只有
b2World
可以创建b2Body
所以这不会去任何地方。这些类显然不是为了继承而设计的,所以是的,应该聚合它们。类似的事情怎么样Only
b2World
can create ab2Body
so this just doesn't go anywhere. These classes clearly aren't designed to be inherited from so yes, aggregate them instead. What about something along the lines of