无法访问单例类析构函数中的私有成员 [英] Cannot access private member in singleton class destructor

查看:181
本文介绍了无法访问单例类析构函数中的私有成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图实现这个单例类。但我遇到这个错误:

I'm trying to implement this singleton class. But I encountered this error:

'Singleton ::〜Singleton':无法访问在'Singleton'类中声明的私有成员
这是在头文件,包含右括号的最后一行。

'Singleton::~Singleton': cannot access private member declared in class 'Singleton' This is flagged in the header file, the last line which contains the closing brace.

有人可以帮我解释导致这个问题的原因吗?
以下是我的源代码。

Can somebody help me explain what is causing this problem? Below is my source code.

Singleton.h:

Singleton.h:


class Singleton
{
public:
    static Singleton* Instance()
    {
        if( !pInstance )
        {
            if( destroyed )
            {
                // throw exception
            }
            else
            {
                Create();
            }

        }
        return pInstance;
    }
private:
    static void Create()
    {
        static Singleton myInstance;
        pInstance = &myInstance;
    }
    Singleton() {}
    Singleton( const Singleton& );
    Singleton& operator=( const Singleton& );
    ~Singleton() 
    {
        pInstance = 0;
        detroyed = false;
    }

    static Singleton* pInstance;
    static bool destroyed;
};

Singleton.cpp:

Singleton.cpp:


Singleton* Singleton::pInstance = 0;
bool Singleton::destroyed = false;

在我的主要功能内:


Singleton* s = Singleton::Instance();

如果我把析构函数设为public,那么问题就消失了。但是一本书(Modern C ++ Design)说它应该是私有的,以防止用户删除实例。我实际上需要为pInstance清除一些代码并在析构函数中销毁。

If I make the destructor as public, then the problem disappears. But a book (Modern C++ Design) says it should be private to prevent users from deleting the instance. I actually need to put some code for cleanup for pInstance and destroyed inside the destructor.

顺便说一句,我使用Visual C ++ 6.0编译。

By the way, I'm using Visual C++ 6.0 to compile.

推荐答案

你应该让我们知道你正在使用的Visual C ++的版本是VC6。我可以重现这个错误。

You should probably have let us know that the version of Visual C++ you're working with is VC6. I can repro the error with that.

在这一点上,除了可能的话,我没有建议移动到较新版本的MSVC(VC 2008可用

At this point, I have no suggestion other than to move up to a newer version of MSVC if possible (VC 2008 is available at no cost in the Express edition).

只是几个其他数据点 - VC2003和更高版本没有问题与 Singleton 析构函数在你的示例中是私有的。

Just a couple other data points - VC2003 and later have no problem with the Singleton destructor being private as in your sample.

这篇关于无法访问单例类析构函数中的私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆