我有一个基类与几个公共方法,并希望派生一个继承只有某些功能的子类,所以我派生子类使用私有继承。此外,我曾多次遇到过(包括C++ primer plus),它的私有继承几乎和遏制一样。现在我遇到了一个问题,我想在基类中定义的函数在派生类中可用。私有继承或遏制
除了基类所要求的类之外,派生类没有任何私有成员。我不确定如何为代码中显示的派生类定义公共方法“func”。
class Base
{
private:
double *p;
public:
Base(int m, int n);
void fun(const Base & obj1, const Base & obj2)
};
class Derived : private Base
{
public:
Derived(int n) : Base(1,n) {}
void fun(const Derived & obj1,const Base & obj2)
{
/* The function fun in derived class works almost exactly
like fun in Base class but I don't know how to call
Base.Fun(...). Also all the data needed to perform
operations in this function is a part of the private
member of the base class which the Derived member can't
access.
*/
}
}
如果我用我围堵可能刚才定义如下:
class Derived
{
private:
Base P;
public:
void fun(const Derived & obj1,const Base & obj2)
{
Base :: P.func(obj1.P,obj2);
}
};
这让我怀疑遏制是比较合适的,这里比私有继承。另一方面,我不确定任何一种实现是否正确。所以我正在寻找可能的方法来做到这一点。
请注意,我没有在上面的代码中显示复制构造函数,赋值和运算符以及其他一些方法,但我知道它们的要求。代码只是为了显示私有继承和遏制的基本目的。
[何时使用C++私有继承而不是组合?](https://stackoverflow.com/questions/6297331/when-to-use-c-private-inheritance-over-composition) – Raedwald