gpt4 book ai didi

c++ - 特殊双向关联

转载 作者:行者123 更新时间:2023-11-28 08:15:04 25 4
gpt4 key购买 nike

我认为这叫做反身联想,但我不太确定。

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

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

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

我想在类 CGame 中创建一个 CFigure 的对象,以便 CFigures 知道 CGame,反之亦然。为什么它不能与“this”一起使用?我需要做什么来解决这个问题?

提前致谢!

最佳答案

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

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

关于c++ - 特殊双向关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7930734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com