使用声明是否应该隐藏继承的虚函数? [英] Is a using-declaration supposed to hide an inherited virtual function?

查看:161
本文介绍了使用声明是否应该隐藏继承的虚函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  struct level0 
{
virtual void foo()= 0;
};

struct level1:level0
{
virtual void foo(){cout<<level1<< ENDL; }
};

struct level2:level1
{
virtual void foo(){cout<<level2<< ENDL; }
};

struct level3:level2
{
使用level1 :: foo;
};

int main()
{
level1 * l1 = new level3;
l1-> foo();
level3 l3;
l3.foo();
返回0;
}

使用gcc的上述代码给出

  level2 
level1

但在icc中给出

  level2 
level2

哪一个是正确的?或者是未定义的标准?

编辑:
这证明有一个错误当然,请考虑以下主要功能:

  int main()
{
level3 l3;
l3.foo(); //打印level1

level3 * pl3 =& l3;
pl3-> foo(); //打印level2

level3& r13 = 13;
rl3.foo(); //打印level1

level3& rpl3 = * pl3;
rpl3.foo(); //打印level2

return 0;





$ b

所以当直接使用同一个对象时会产生不同的结果,当通过指针使用时相同类型的结果会产生不同的结果!!!标准部分10.3p2中的一个例子清楚地表明使用声明 覆盖虚拟函数。



这是已知的g ++ bug 正如你注意到的,当通过引用或指针调用成员函数时,而不是在知道动态类型的情况下,错误不会发生。


struct level0
{
  virtual void foo() = 0;
};

struct level1 : level0
{
  virtual void foo() { cout <<" level1  " << endl; }
};

struct level2 : level1
{
  virtual void foo() { cout <<" level2 " << endl; }
};

struct level3 : level2
{
  using level1::foo;
};

int main()
{
  level1* l1 = new level3;
  l1->foo();
  level3 l3;
  l3.foo();
  return 0;
}

the above code using gcc gives

level2
level1

but in icc gives

 level2
 level2

Which one is correct or is it undefined by standard?

Edit: This proves there is a bug for sure, consider the following main function

int main()
{
    level3 l3;
    l3.foo();               // This prints level1

    level3* pl3 = &l3;
    pl3->foo();             // This prints level2

    level3& rl3 = l3;
    rl3.foo();              // This prints level1

    level3& rpl3 = *pl3;
    rpl3.foo();             // This prints level2

    return 0;
}

So the same object when used directly produces different results and when used via a pointer of same type produces different results!!!

解决方案

An example in Standard section 10.3p2 makes it clear that using declarations do not override virtual functions.

This is a known g++ bug.

As you noticed, when calling the member function via a reference or pointer, rather than a case in which the dynamic type is known, the bug does not happen.

这篇关于使用声明是否应该隐藏继承的虚函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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