无法从该对象继承?

发布于 2024-08-07 13:09:42 字数 1348 浏览 9 评论 0原文

跟进这个问题,人们有建议我选择“选项 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:

  1. Body 永远无法被构造,即使使用 World::CreateBody (因为 b2Body 是私有的)
  2. 即使可以,那么 b2Body 部分无法正确初始化(b2World::CreateBody 需要被调用)

这是否意味着我永远不能从 b2Body< 继承/code>/b2World 并遵循相同的设计模式? (请记住,我无法编辑 b2* 类)

如果是这样,我想你们会建议我只保留 b2Worldb2Body 作为成员变量?


我认为现在归结为这两个选项:

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;
}

Try it online

But there are two major problems with this:

  1. Body can never be constructed, even with World::CreateBody (because b2Body is private)
  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眉目亦如画i 2024-08-14 13:09:42

只有 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;
};

Only b2World can create a b2Body 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

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;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文