从不同的基类重载同名的虚函数。是否可以?
标题可能令人困惑。
假设我们有以下设置;
class A
{
public:
virtual void fn() = 0;
};
class B
{
public:
virtual int fn() {};
};
class C: public A, public B
{
};
有没有办法在class C
中定义A::fn
?
The title is probably confusing.
Suppose we have the following set up;
class A
{
public:
virtual void fn() = 0;
};
class B
{
public:
virtual int fn() {};
};
class C: public A, public B
{
};
Is there any way to define A::fn
in class C
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C
中无法指定C::fn()
之一实现重载
A::fn()
(大概还有另一个重载B::fn()
)。然而,你可以做的是引入一个中间层“重命名”函数的类,例如:
There's no way in
C
to specify that one of theC::fn()
implementations overloads
A::fn()
(and presumably another overloadsB::fn()
). What you can do, however, is introduce an intermediateclass which “renames” the functions, something like:
不。这是不可能的。它总是与
fn()
中的任何一个发生冲突。fn()
的语法不同,在
B
中,您必须使
A
和B< 中的语法相同/code> 让
C
实现fn()
。 演示。No. This is not possible. It will always conflict with either of the
fn()
.The syntax of
fn()
are different,and in
B
is,You have to make those syntax same in
A
andB
to letC
implement thefn()
. Demo.您可能想阅读我对以下问题的回答:由于多个抽象基类,实现两个同名但不同、非协变返回类型的函数
简而言之:是的,但调用它有一些限制。它可以被称为 A(指针或引用)或 B(指针或引用),但不能被称为 C,因为那样会产生歧义。
You might want to read my answer to the following question: Implement two functions with the same name but different, non-covariant return types due to multiple abstract base classes
In short: Yes, with some restrictions on calling it. It can be called as an A (pointer or reference) or a B (pointer or reference), but not as a C, as that would be ambiguous.