gpt4 book ai didi

c++ - 前向声明的单例类,带有来自具有前向声明的类的友元函数

转载 作者:太空宇宙 更新时间:2023-11-04 15:56:35 24 4
gpt4 key购买 nike

我希望这是一个连贯的问题......我有一个单例类定义:

#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();
}

类定义是:

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

Singleton::~Singleton() {}

Singleton::Singleton() {}

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

我的 A 类声明是:

#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.
}

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

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

最佳答案

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

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

    Singleton& mSingleton; 

    然后

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

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

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

Singleton::getInsance().methodOnlyNeededByA();

关于c++ - 前向声明的单例类,带有来自具有前向声明的类的友元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56310748/

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