C++同名的虚拟覆盖函数
我有类似的东西(简化)
class A
{
public:
virtual void Function () = 0;
};
class B
{
public:
virtual void Function () = 0;
};
class Impl : public A , public B
{
public:
????
};
如何实现 A 的 Function () 和 B 的 Function() ? Visual C++ 允许您仅内联定义特定函数(即不在 cpp 文件中), 但我认为这是一个扩展。 GCC对此有所抱怨。 是否有标准的 C++ 方法来告诉编译器我要覆盖哪个函数?
(Visual C++ 2008)
class Impl : public A , public B
{
public:
void A::Function () { cout << "A::Function" << endl; }
void B::Function () { cout << "B::Function" << endl; }
};
谢谢!
I have something like that (simplified)
class A
{
public:
virtual void Function () = 0;
};
class B
{
public:
virtual void Function () = 0;
};
class Impl : public A , public B
{
public:
????
};
How can I implement the Function () for A and the Function() for B ?
Visual C++ lets you only define the specific function inline (i.e. not in the cpp file),
but I suppose it's an extension. GCC complains about this.
Is there a standard C++ way to tell the compiler which function I want to override?
(visual c++ 2008)
class Impl : public A , public B
{
public:
void A::Function () { cout << "A::Function" << endl; }
void B::Function () { cout << "B::Function" << endl; }
};
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果 A 和 B 是接口,那么我将使用虚拟派生来“连接”它们(使它们重叠)。如果您需要通过指向
A
或B
的指针调用Function
的不同实现,那么我强烈建议您选择其他设计。否则会受伤。Impl
“派生自”A
和B
表示Impl
“是”A
和B
。我想你不是这个意思。Impl
“实现接口”A
和B
表示Impl
“行为类似于”A
和B
。那么相同的接口应该意味着相同的行为。在这两种情况下,根据所使用的指针类型而具有不同的行为将是“精神分裂的”,并且肯定是要避免的情况。
If A and B are interfaces, then I would use virtual derivation to "join" them (make them overlap). If you need different implementations for your
Function
if called through a pointer toA
or toB
then I would strongly recommend to choose another design. That will hurt otherwise.Impl
"derives from"A
andB
meansImpl
"is a"A
andB
. I suppose you do not mean it.Impl
"implements interface"A
andB
meansImpl
"behaves like"A
andB
. then same interface should mean the same behavior.In both cases having a different behavior according to the type of pointer used would be "schizophrenic" and is for sure a situation to avoid.
您不能在那里使用限定名称。如果您编写
void Function() { ... }
,您将覆盖两个函数。 Herb Sutter 展示了如何解决该问题。另一种选择是重命名这些函数,因为显然它们做了不同的事情(否则我看不到以相同行为覆盖两者的问题)。
You cannot use qualified names there. I you write
void Function() { ... }
you are overriding both functions. Herb Sutter shows how it can be solved.Another option is to rename those functions, because apparently they do something different (otherwise i don't see the problem of overriding both with identical behavior).
我可以建议另一种方法来解决这个问题。您可以添加包装器
Typed
,它通过添加虚拟参数来更改Function
签名。因此,您可以区分实现中的方法。这种解决方案的好处是所有实现都放在一个类中。
I can suggest another way to resolve this issue. You can add wrapper
Typed
which changesFunction
signature by adding dummy parameter. Thus you can distinguish methods in your implementation.The benefit of such solution is that all implementation are placed in one class.
作为解决方法,请尝试
As a workaround, try