考虑以下无效的 C++ 代码。
#include <assert.h>
class NodeInterface {
public:
virtual ~NodeInterface () {}
virtual int f (const int& n) const = 0;
};
class ChildNodeInterface : public NodeInterface {
public:
virtual ~ChildNodeInterface () {}
};
class ParentNodeInterface : public NodeInterface {
public:
virtual ~ParentNodeInterface () {}
};
class ChildNode : public ChildNodeInterface {
public:
virtual ~ChildNode () {}
virtual int f (const int& n) const {
return 2*n;
}
};
class ParentNode : public ParentNodeInterface, private ChildNodeInterface {
public:
explicit ParentNode () :
mChild (new ChildNode ())
{
}
virtual ~ParentNode () {}
ChildNodeInterface* GetChildHandle () {
return this;
}
virtual int f (const int& n) const {
return 3*n;
}
private:
ChildNode* const mChild;
// How do I specify that I would like to override ChildNodeInterface::f?
virtual int f (const int& n) const { // On MSVC2010: C2535 member function already defined or declared
return 1 + mChild->f (n);
}
};
int main()
{
ParentNode parent;
assert (parent.f (2) == 6);
ChildNode node;
assert (node.f (2) == 4);
ChildNodeInterface* child (parent.GetChildHandle ());
assert (child->f (2) == 5);
return 0;
}
我的目标是让ParentNode
私下看起来像一个ChildNode
,这样它就可以ChildNode
在ChildNodeInterface
. ParentNode
因此可以有效地被视为ChildNode
变相的-句柄,由 的简单性表示GetChildHandle
。显然,如果ParentNode
不重复从 继承NodeInterface
,就不会有问题。因为,人们可以很容易地消除覆盖的歧义。以下正确示例说明了这一点:
#include <assert.h>
class ChildNodeInterface {
public:
virtual ~ChildNodeInterface () {}
virtual int ChildMethod (const int& n) const = 0;
};
class ParentNodeInterface {
public:
virtual ~ParentNodeInterface () {}
virtual int ParentMethod (const int& n) const = 0;
};
class ChildNode : public ChildNodeInterface {
public:
virtual ~ChildNode () {}
virtual int ChildMethod (const int& n) const {
return 2*n;
}
};
class ParentNode : public ParentNodeInterface, private ChildNodeInterface {
public:
explicit ParentNode () :
mChild (new ChildNode ()),
mValue (1)
{
}
ChildNodeInterface* GetChildHandle () {
return this;
}
virtual int ParentMethod (const int& n) const {
return 3*n;
}
private:
ChildNode* const mChild;
const int mValue;
virtual int ChildMethod (const int& n) const {
return mValue + mChild->ChildMethod (n);
}
};
int main()
{
ParentNode parent;
assert (parent.ParentMethod (2) == 6);
ChildNode node;
assert (node.ChildMethod (2) == 4);
ChildNodeInterface* child (parent.GetChildHandle ());
assert (child->ChildMethod (2) == 5);
return 0;
}
ParentNodeInterface
但是,在和ChildNodeInterface
都继承自的特殊情况下,NodeInterface
就会出现歧义。从 中的断言中应该可以清楚地看出main
,我的目标不是虚拟继承NodeInterface
. 我打算对NodeInterface::f
in进行真正不同的实现ParentNode
。我想知道(如果可能的话)我如何区分ParentNodeInterface::f
和ChildNodeInterface::f
in的实现ParentNode
。