结论:
- d指针指向private类
- q指针指向public类
FooClass.h
#include"FooClassPrivate.h"
template <typename T> static inline T *qGetPtrHelper(T *ptr) { return ptr; }
#define Q_DECLARE_PRIVATE(Class) \
inline Class##Private* d_func() { return reinterpret_cast<Class##Private *>(qGetPtrHelper(d_ptr)); } \
inline const Class##Private* d_func() const { return reinterpret_cast<const Class##Private *>(qGetPtrHelper(d_ptr)); } \
friend class Class##Private;
#define Q_D(Class) Class##Private * const d = d_func()
class FooClass{
public:
FooClass():d_ptr(new FooClassPrivate(this)){}
virtual ~FooClass()
{
Q_D(FooClass);
delete d;
}
int getID(){
Q_D(FooClass);
return d->getID();
}
void setID(int id){
Q_D(FooClass);
d->setID(id);
}
private:
FooClassPrivate* const d_ptr;
Q_DECLARE_PRIVATE(FooClass)
};
FooClassPrivate.h
class FooClass;
#define Q_DECLARE_Public(Class) \
inline Class* q_func() { return reinterpret_cast<Class *>(q_ptr); } \
inline const Class* q_func() const { return reinterpret_cast<const Class *>(q_ptr); } \
friend class Class;
#define Q_Q(Class) Class * const q = q_func()
class FooClassPrivate{
public:
FooClassPrivate(FooClass* p):q_ptr(p){
}
int getID(){
return _id;
}
void setID(int id){
_id = id;
}
virtual ~FooClassPrivate(){}
private:
FooClass* const q_ptr;
int _id = 0;
Q_DECLARE_Public(FooClass)
};
main.cpp
#include <iostream>
#include "FooClass.h"
int main(){
FooClass* foo = new FooClass();
std::cout << "ID = " << foo->getID() << std::endl;
foo->setID(10);
std::cout << "ID = " << foo->getID() << std::endl;
return 0;
}
运行测试
g++ -o main main.cpp
./main