在 C++ 中,如何在没有循环引用(或丢失类型)的情况下将 `this` 传递给构造函数?

How can I pass `this` to a constructor without circular references (or losing type) in c++?

编辑:这已被标记为重复。我相信 Q:我可以用什么来解决我的问题,A:这个东西 ~ 和~ Q:这个东西是什么? A:大而深的答案。不过我不确定官方对此的裁决是什么。

我有两个 class 需要相互了解

// Creator.h
#pragma once
#include "Creation.h"
class Creator {
  Creator() {
    myThing = new Creation(*this);
  }
  int age = 42;
  Creation myThing*;
}

.

// Creation.h
#pragma once
#include "Creator.h"
class Creation {
  Creation(Creator &whoMadeMe) {
    std::cout << whoMadeMe.age;
  }
}

问题是每当我做这样的事情时,我都会得到一个错误,说其中一个或另一个还不存在。在这种情况下,Creation(Creator &whoMadeMe) 会给出错误 Creator does not exist,因为创建 class 尚未准备好引用。

直到现在,我总能找到一种方法让只有一个 class 知道另一个,或者可能使用一些父 class 来避免引用 class哪个引用回来。但我在这里陷入僵局,我需要这两个 class 了解彼此及其属性,我需要一个来创建另一个。

因此,在这种情况下,必须将 this 指针传递给构造函数,如何在不创建循环引用或不必 lose/recast打字?

此外,如果 losing/recasting 打字是最好的解决方案,请告诉我。我总是被告知要避免它,因此我假设它不是解决方案。

您需要将声明(在 .h 文件中)和实现(在 .cpp 文件中)分开。然后在头文件中使用前向声明来防止循环引用。在实施文件中,您可以使用 include。

它将解决您的问题,同时优化您的编译。

检查What are forward declarations in C++? and Separating class code into a header and cpp file

只要您不使用 class 而只是将属性或参数声明为指向 class 的指针或引用,您可以使用 class Creator; 而不是 #include "Creator.h"

不确定这是最佳做法,但您可以使用 template 来解决此问题

#include <iostream>

class Creation 
{
public:
    template<typename Creator> // type concept of Creater
    Creation(Creator &whoMadeMe) 
    {
        std::cout << whoMadeMe.age;
    }
};

class Creator 
{
public:
    Creator()
    {
        myThing = new Creation(*this);
    }
    int age = 42;
    Creation * myThing = nullptr;
};

神箭link: https://godbolt.org/z/ILbFpS

顺便说一句,小心使用new。或者使用智能指针让生活更轻松。