如何使用 Pimpl 授予 public 成员访问权限?
How to give access to public members with Pimpl?
- pimpl.h
#include <memory>
class MyClassImpl;
class MyClass {
void Foo();
struct MyStruct {
int a;
int b;
} variable_struct;
private:
std::unique_ptr<MyClassImpl> m_pImpl;
};
- pimpl.cpp
class MyClassImpl
{
public:
void DoStuff() { /*...*/ }
struct MyStructImpl {
int a;
int b;
} variable_struct_impl;
};
// MyClass (External/User interface)
MyClass::MyClass () : m_pImpl(new MyClassImpl()) { }
MyClass::~MyClass () = default;
void MyClass::Foo() {
m_pImpl->DoStuff();
}
- How/What 将实施的 public 成员分享给 Pimpl class(最终用户)的最佳实践?
- 如果他们有不同的名字,就像在我的示例中
struct MyStruct
和 struct MyStructImpl
(variable_struct
/ variable_struct_impl
) 怎么办?
对于methods,说的很清楚了,反正我们还是要做forward方法。 (示例中 Foo()
转发到 DoStuff()
)
How to give access to public members with Pimpl?
你不知道。 PIMPL 的要点是隐藏 Private IMPLementation 的所有成员,public 访问它们完全违背了这一点。
如果您想要公开访问,请不要将成员放入 PIMPL。
- pimpl.h
#include <memory>
class MyClassImpl;
class MyClass {
void Foo();
struct MyStruct {
int a;
int b;
} variable_struct;
private:
std::unique_ptr<MyClassImpl> m_pImpl;
};
- pimpl.cpp
class MyClassImpl
{
public:
void DoStuff() { /*...*/ }
struct MyStructImpl {
int a;
int b;
} variable_struct_impl;
};
// MyClass (External/User interface)
MyClass::MyClass () : m_pImpl(new MyClassImpl()) { }
MyClass::~MyClass () = default;
void MyClass::Foo() {
m_pImpl->DoStuff();
}
- How/What 将实施的 public 成员分享给 Pimpl class(最终用户)的最佳实践?
- 如果他们有不同的名字,就像在我的示例中
struct MyStruct
和struct MyStructImpl
(variable_struct
/variable_struct_impl
) 怎么办?
- 如果他们有不同的名字,就像在我的示例中
对于methods,说的很清楚了,反正我们还是要做forward方法。 (示例中 Foo()
转发到 DoStuff()
)
How to give access to public members with Pimpl?
你不知道。 PIMPL 的要点是隐藏 Private IMPLementation 的所有成员,public 访问它们完全违背了这一点。
如果您想要公开访问,请不要将成员放入 PIMPL。