前向声明的单例 class 带有前向声明的 class 的友元函数

Forward declared singleton class with a friend function from the class with the forward declaration

我希望这是一个连贯的问题...我有一个单身人士 class 定义如下:

#include A.h

class Singleton
{
public:
   // If I change this to a return by pointer, it works fine. But reference gives me problems.
   static Singleton &getInstance();
   Singleton(Singleton const&) = delete;
   void operator=(Singleton const&) = delete;
   ~Singleton();

   friend void A::friendMethodinA();
private:
   Singleton();
   void methodOnlyNeededByA();
}

class定义是:

Singleton &Singleton::getInstance()
{
   static Singleton instance;
   return instance;
}

Singleton::~Singleton() {}

Singleton::Singleton() {}

void Singleton::methodOnlyNeededByA() { // method body. }

我的class一个声明是:

#pragma once

class Singleton;

class A
{
public:
   void friendMethodinA();
private:
   // This is what I'm not sure about. I tried
   // Singleton &mSingleton = Singleton::getInstance(); This gives me "use of undefined type 'Singleton'" error. I can't #include Singleton.h because of the friend function.
   // Singleton mSingleton = Singleton::getInstance(); This gives me "cannot be reference -- it is a deleted function" error.
   Singleton mSingleton; // This gives me "A::mSingleton uses undefined class 'Singleton'" error.
}

我真的很想 return 通过引用而不是指针 b 来 return 单例,以避免在我每次使用它时进行空检查和取消引用指针。有没有办法在不完全重构以避免使用友元函数的情况下实现这一目标?

这个友元函数的目的是方法methodOnlyNeededByA()。因为它只需要被 Class A 调用,所以我不想把它放在 Singleton 的 public 接口中。

您可以通过以下方式解决编译器错误:

  1. 使用引用类型作为成员变量。

    Singleton& mSingleton; 
    

    然后

  2. 正在构造函数中初始化它。

不过,我想说的更重要的一点是:不要使用Singleton类型的成员变量。当您需要使用 class 时,只需调用 Singleton::getInstance()。您可以将对返回对象的引用存储在函数局部变量中,或者只使用返回的引用。

auto& ref = Singleton::getInsance();
ref.methodOnlyNeededByA();

Singleton::getInsance().methodOnlyNeededByA();