特殊双向协会

时间:2011-10-28 14:39:13

标签: c++

我认为它被称为反身联想,但我不太确定。

这是代码(应该看看什么是重要的):

CGmae::CGame(void)
{
    CFigure * figure = new CFigure(this);
}

CFigure::CFigure(CGame * game)
{
    CGame * game = game;
}

我想在CGame类中创建一个CFigure对象,这样CFigures知道CGame,反之亦然。为什么不使用'this'?我需要做些什么才能解决问题?

提前致谢!!

1 个答案:

答案 0 :(得分:1)

对我来说很好(添加了惯用的改进和拼写检查):

struct CGame;

struct CFigure
{
  CGame * cg;
  CFigure(CGame * p) : cg(p) { }
};

struct CGame
{
  CFigure * cf;
  CGame() : cf(new CFigure(this)) { }
};  // better be sure to understand memory leaking and exceptions...

CGame g; // works
相关问题