我在将工作 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 );
^
你对这个任务有什么建议吗?很感谢