I would like to better understand how to use static field an method in the presence of PIMPL idiom. Consider the following code.
MyClass.h file:
#ifndef MYCLASS
#define MYCLASS
class MyClass{
public:
void method();
static void static_method();
private:
Type field;
static Type *static_field;
}
#endif
MyClass.cpp file:
#include MyClass.h
void MyClass::method(){
/*OK method definition*/
field = new Type(); /*OK field construction*/
}
void MyClass::static_method(){
/*NOT WORKING method declaraion */
static_field = new Type(); /*not working */
}
I have these 2 errors:
- cannot declare member function static_method to have a static linkage
- static_field was not declared in this scope
I'm not very familiar with pimpl idiom.
So my question is how I achieve static methods and fields declarati开发者_StackOverflowons to respect the PIMPL idiom and compile it successfully?
What am I doing wrong in this code?
How have I to change my code?
The purpose if pimpl is to eliminate compilation dependencies. The fact that a pimpl class has a private static member is an implementation detail and thus should not be in the header file or in the pimpl class definition.
Put you private statics into the .cc/.cpp file in an unnamed namespace along with the definitions of the member functions of the pimpl class.
- Show us actual code that you've verified produces the same error
- Don't put static in front of the function definition in the .cpp file
- You don't have a
static_field
- you have twofield
Indeed, u need to have the definiton
Type* MyClass::static_field = new Type();
at u'r cpp file. this is because this way u tell the compiler at what object file the field should be instantiated, otherwise the compiler has no way to know.
精彩评论