This question already has answers here:
Resolve build errors due to circular dependency amongst classes
                                
                                    (11个答案)
                                
                        
                                2年前关闭。
            
                    
我对C ++很陌生,遇到了以下问题:

class School
{
 Manager manager;
}

class Manager
{
 School school;
}


这将需要无限的内存,并会导致不必要的无限循环。

解决问题的最佳方法是什么?

最佳答案

class School;
class Manager
{
    std::weak_ptr<School> school;
};
class School
{
    std::shared_ptr<Manager> manager;
};


根据您要执行的操作,您可能想使用Manager中的shared_ptr和School中的weak_ptr,但是概念保持不变。

关于c++ - C++-相互对象包含,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46700660/

10-12 19:47