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:
I'm not very familiar with pimpl idiom.
So my question is how I achieve static methods and fields declarations 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.
static_field
- you have two field
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.