为什么虚函数被隐藏?

编程入门 行业动态 更新时间:2024-10-25 02:30:59
本文介绍了为什么虚函数被隐藏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下类:

class A { public: virtual void f ){} }; class B:public A { public: void f(int x){} };

如果我说

B * b = new B(); b-> f();

编译器说错误C2660:'B :: f':function不接受0个参数。 不应该在B的函数重载它,因为它是一个虚函数?

EDIT :我的确想要从A继承B,它显示了相同的行为。

解决方案

假设您希望 B 从 / code>:

f(int)和 f / code>是不同的签名,因此具有不同的功能。

您可以使用具有兼容签名的函数覆盖< ,这意味着相同的签名,或者其中返回类型是更具体(这是协方差)。

否则,您的派生类函数隐藏虚拟函数,就像其他派生类声明与基类函数同名的函数一样。您可以使用A :: f; c>在B类中放置以取消隐藏

(static_cast< A *(b)) - > f(); 或者 b-> A :: f ; 。区别是如果 B 实际上覆盖 f(),则前者调用覆盖,而后者调用 A 中的函数,无论。

I have the following classes:

class A { public: virtual void f() {} }; class B : public A{ public: void f(int x) {} };

If I say

B *b = new B(); b->f();

the compiler says error C2660: 'B::f' : function does not take 0 arguments. Shouldn't the function in B overload it, since it is a virtual function? Do virtual functions get hidden like this?

EDIT: I indeed meant to inherit B from A, which shows the same behaviour.

解决方案

Assuming you intended B to derive from A:

f(int) and f() are different signatures, hence different functions.

You can override a virtual function with a function that has a compatible signature, which means either an identical signature, or one in which the return type is "more specific" (this is covariance).

Otherwise, your derived class function hides the virtual function, just like any other case where a derived class declares functions with the same name as base class functions. You can put using A::f; in class B to unhide the name

Alternatively you can call it as (static_cast<A*>(b))->f();, or as b->A::f();. The difference is that if B actually does override f(), then the former calls the override, whereas the latter calls the function in A regardless.

更多推荐

为什么虚函数被隐藏?

本文发布于:2023-06-12 05:19:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/652094.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!