0

我在将工作 pimpl 类转换为单例时遇到了一些麻烦。这是起始代码:

apirequest.h

class ApiRequestPrivate;

class ApiRequest
{
public:

    ApiRequest( int );
    ~ApiRequest( );

    int method1();

private:
    ApiRequestPrivate* const d;
};

apirequest_p.h

#include "apirequest.h"

class ApiRequestPrivate
{
public:
    ApiRequestPrivate( int );

    int method1();

private:
    int member1;
};

apirequest.cpp

#include "apirequest.h"
#include "apirequest_p.h"

ApiRequestPrivate::ApiRequestPrivate( int value )
{
    member1 = value;
}

int ApiRequestPrivate::method1( )
{
    return member1;
}

ApiRequest::ApiRequest( int value ) : d( new ApiRequestPrivate( value ) )
{
}

ApiRequest::~ApiRequest()
{
    delete d;
}

int ApiRequest::method1( )
{
    return d->method1( );
}

首先,我做了以下修改:

apirequest.h

class ApiRequest
{
public:
    ~ApiRequest( );

    static ApiRequest * getApiRequest(int);

    int method1();

private:
    ApiRequestPrivate* const d;
    ApiRequest( int );
};

apirequest_p.h

class ApiRequestPrivate
{
public:
    ...
    static ApiRequest * getApiRequest(int);

private:
    ...
    static ApiRequest * m_apiRequest;
};

apirequest.cpp

...

ApiRequest * ApiRequestPrivate::getApiRequest( int value )
{
    if(m_apiRequest == 0) {
        m_apiRequest = new ApiRequest( value );
    }

    return m_apiRequest;
}

...

ApiRequest * ApiRequest::getApiRequest( int value )
{
    return d->getApiRequest( value );
}

但编译失败并出现各种错误,其中第一个是:

In file included from apirequest.cpp:1:0:
apirequest.h: In static member function ‘static ApiRequest* ApiRequestPrivate::getApiRequest(int)’:
apirequest.h:17:5: error: ‘ApiRequest::ApiRequest(int)’ is private
     ApiRequest( int );
     ^
apirequest.cpp:17:46: error: within this context
         m_apiRequest = new ApiRequest( value );
                                              ^

然后我尝试将 ApiRequest() 构造函数移回公共,编译失败,代码如下:

In file included from apirequest.cpp:1:0:
apirequest.h: In static member function ‘static ApiRequest* ApiRequest::getApiRequest(int)’:
apirequest.h:17:30: error: invalid use of member ‘ApiRequest::d’ in static member function
     ApiRequestPrivate* const d;
                              ^
apirequest.cpp:39:12: error: from this location
     return d->getApiRequest( value );
            ^

你对这个任务有什么建议吗?很感谢

4

1 回答 1

1

第一个是因为您尝试ApiRequest使用来自另一个类的私有构造函数来创建ApiRequestPrivate. 据推测,构造函数希望是私有的,以支持您认为想要的任何基于单例的精神错乱;所以一个解决办法是交ApiRequestPrivate个朋友ApiRequest

或者,您可以在ApiRequest::getApiRequest. 将该函数的实现移到私有类中是没有意义的。

二是因为函数是静态的,所以没有对象可以访问其成员。但是,您调用的函数也是静态的,因此您不需要该对象:

return ApiRequestPrivate::getApiRequest(value);

但是,再一次,引入这个额外的功能真的没有意义。

我还想知道如果您想将一个值传递给函数以创建请求,然后在下一次传递一个不同的值会发生什么。如果这需要改变,那么单例可能比通常情况下更糟糕。

于 2013-10-08T16:10:47.447 回答