将 class 的引用声明为 class 成员

Declare reference to class as class member

我想将对 class 的引用声明为类似于指向 class 的指针作为它自己的成员变量。以下是我编写的代码,但我现在不知道如何进一步创建这样一个 class 的对象,因为即使我编写了默认构造函数或仅初始化 [=13] 的构造函数,编译器也会始终给出错误=].

class Test2
{
private:
    Test2& testRef;
    int var;

public:
    Test2( int x, Test2 testObj ) : var( x ), testRef( testObj )
    {

    }
};

我需要进一步做些什么来创建这样的对象 class 或者根本不可能这样做。如果不可能,为什么编译器不简单地给出一个错误说 you can't have reference to the own class

您尝试将对象的临时副本传递给引用。 如果你在构造函数中传递引用,就可以了:

Test2( int x, Test2& testObj ) : var( x ), testRef( testObj )
{

}

附加问题:您需要引用非 const 吗? 如果您不修改对象,最好使用对象的 const 引用 :

class Test2
{
  private:
    const Test2& testRef;
  public:
    Test2( int x, const Test2& testObj ) : var(x), testRef(testObj) {}
};

私人: 测试2&测试参考; 整数变种;

public: Test2( int x, Test2 testObj ) : var( x ), testRef( testObj ) {

}

};

此外,您应该按照声明的顺序进行初始化:

Test2(int x, const Test2& testObj) : testRef(testObj), var(x) {}

如果你有一个引用成员,你必须在所有的构造函数中初始化它,因为引用必须被初始化。甚至你的默认构造函数。由于您创建的 class 的第一个对象将没有任何其他可以引用的对象,因此您必须将其引用到自身。例如:

Test2() :testRef(*this) {}