[英]Friend, Forward Declaration, C++
So this is confusing me a little.所以这让我有点困惑。 Neither will be declared before the other, incomplete types or such.
两者都不会在其他不完整类型等之前声明。
Game
won't go before Hero
because of Hero test1
.由于
Hero test1
, Game
不会在Hero
之前 go 。 Hero
won't go before Game
because of friend void Game::vitals(Hero&);
由于朋友无效,
Hero
在游戏前不会 go Game
friend void Game::vitals(Hero&);
Is this an impossible circular dependency?这是不可能的循环依赖吗?
class Game
{
// ...
void vitals(Hero&);
Hero test1;
};
class Hero : public Character
{
// ...
public:
friend void Game::vitals(Hero&);
};
So Hero
must go before Game
because class Game {... Hero test1; ... };
所以
Hero
必须在Game
前 go 因为class Game {... Hero test1; ... };
class Game {... Hero test1; ... };
requires Hero
to be fully defined.需要完全定义
Hero
。
But friend void Game::vitals(Hero&);
但是
friend void Game::vitals(Hero&);
can simply be reworked as friend class Game;
可以简单地重做为
friend class Game;
. . Making one method of one class as a friend of another is rarely used, and doesn't make much sense since any sort of friendship assumes that the two pieces of code 'trust' each other.
将一个 class 作为另一个朋友的一种方法很少使用,并且没有多大意义,因为任何形式的友谊都假设两段代码相互“信任”。 So you might as well make the whole classes friends.
所以你不妨把全班都交朋友。
The alternative work be to rework the design so that no friendship is needed.另一种工作是重新设计设计,这样就不需要友谊了。 It's probably a weakness in your design as it is.
这可能是您设计中的一个弱点。
You can either fix this by making Game
hold a pointer (or something analogous) to Hero
, or by nesting Hero
inside Game
:您可以通过让
Game
持有指向Hero
的指针(或类似的东西)或通过在Game
中嵌套Hero
来解决此问题:
class Game
{
class Hero;
void vitals(Hero&);
class Hero : public Character
{
// ...
public:
friend void Game::vitals(Hero&);
};
Hero test1;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.