Pimpl成语与继承 [英] Pimpl idiom with inheritance
本文介绍了Pimpl成语与继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用带继承的pimpl习语。
I want to use pimpl idiom with inheritance.
这是基础公共类及其实现类:
Here is the base public class and its implementation class:
class A
{
public:
A(){pAImpl = new AImpl;};
void foo(){pAImpl->foo();};
private:
AImpl* pAImpl;
};
class AImpl
{
public:
void foo(){/*do something*/};
};
我希望能够使用其实现类创建派生公共类:
And I want to be able to create the derived public class with its implementation class:
class B : public A
{
public:
void bar(){pAImpl->bar();}; // Can't do! pAimpl is A's private.
};
class BImpl : public AImpl
{
public:
void bar(){/*do something else*/};
};
但是我不能在B中使用pAimpl,因为它是A的私有。
But I can't use pAimpl in B because it is A's private.
所以我看到了一些方法来解决它:
So I see some ways to solve it:
- 在B中创建BImpl * pBImpl成员,并通过它带有附加的A构造函数A(AImpl *)。
- 将pAImpl更改为受保护(或添加Get函数),并在B中使用它。
- B不应该继承自A.在B中创建BImpl * pBImpl成员,并在B中创建foo()和bar(),这将使用pBImpl。
- 任意其他方式?
- Create BImpl* pBImpl member in B, and pass it to A with additional A constructor, A(AImpl*).
- Change pAImpl to be protected (or add a Get function), and use it in B.
- B shouldn't inherit from A. Create BImpl* pBImpl member in B, and create foo() and bar() in B, that will use pBImpl.
- Any other way?
我应该选择什么?
推荐答案
class A
{
public:
A(bool DoNew = true){
if(DoNew)
pAImpl = new AImpl;
};
void foo(){pAImpl->foo();};
protected:
void SetpAImpl(AImpl* pImpl) {pAImpl = pImpl;};
private:
AImpl* pAImpl;
};
class AImpl
{
public:
void foo(){/*do something*/};
};
class B : public A
{
public:
B() : A(false){
pBImpl = new BImpl;
SetpAImpl(pBImpl);
};
void bar(){pBImpl->bar();};
private:
BImpl* pBImpl;
};
class BImpl : public AImpl
{
public:
void bar(){/*do something else*/};
};
这篇关于Pimpl成语与继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文