主导地位的继承-真的不好吗? [英] Inheritance by dominance - is it really bad?

查看:135
本文介绍了主导地位的继承-真的不好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是必须获得其代码才能使用0警告进行编译的人之一.通常,我尊重编译器,如果它向我发出警告,则将其视为我应该稍微修改一下代码的标志.如果我不得不告诉编译器忽略给定的警告,我会抽搐一下.

I'm one of those people that has to get their code to compile with 0 warnings. Normally I respect the compiler and if it issues me a warning I take it as a sign that I should touch up my code a little. If I have to tell a compiler to ignore a given warning, I twitch a little.

但是我似乎无法解决这个问题,从我可以告诉我的情况来看,我还没有做任何不好"的事情.有人认为这是一个糟糕的设计吗?我看不到任何特别令人讨厌的东西(邪恶的钻石"除外),但这是完全有效和有用的代码.但是它会(在MSVC中)生成2级警告!

But this one I can't seem to get around, and from what I can tell I haven't done anything "bad". Does anyone think that this is a poor design? I can't see anything particularly nasty about it (except for the "evil diamond") but it's perfectly valid and useful code. But it generates (in MSVC) a level 2 warning!

class IFoo
{
public:
    virtual void foo() = 0;
};

class Bar : public virtual IFoo
{
public:
    virtual void foo() { std::cout << "Hello, world!"; }
};

class Baz : public virtual IFoo
{

};

class Quux : public Bar, public Baz
{

};

现在,如果我创建一个Quux对象,则应该调用Bar :: foo实现. MSVC非常有帮助:它警告我不够模棱两可?

Now if I create a Quux object it should be expected to call the Bar::foo implementation. MSVC is very helpful: it warns me for not being ambiguous enough?

警告C4250:"Quux":通过优势继承"Bar :: Bar :: foo"

warning C4250: 'Quux' : inherits 'Bar::Bar::foo' via dominance

现在,我意识到我可以通过实用程序关闭此警告,但这不是我要在此处提出的问题.是我应该在这里听编译器的原因,还是仅仅是一个极端的过分警告?

Now I recognize I can turn this warning off with a pragma, but that's not the question I'm trying to ask here. Is there a reason I should be listening to the compiler here, or is this just an extremely overzealous warning?

推荐答案

执行虚拟继承时,不显式重写最派生类中的每个成员是一个坏主意.否则,当有人更改从虚拟基础继承的基础类之一时,您正在要求代码死于可怕的死亡.这没有任何 active 错误,您的程序不会崩溃等,但这不是可维护性的好主意.如果要调用Bar::foo版本,则应在Quux::foo中委派给它.

When performing virtual inheritance, it is a bad idea to not explicitly override every member in the most derived class. Else, you are asking for your code to die a horrible death when someone changes one of your base classes that inherits from the virtual base. There's nothing actively wrong with this, your program won't crash or anysuch, but it's a maintainability bad idea. If you want to call the Bar::foo version, then you should just delegate to it in Quux::foo.

这篇关于主导地位的继承-真的不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆