在C ++中显式隐藏一个基函数 [英] Explicitly hide a base function in C++
问题描述
C ++ 11引入了非常有用的说明符 override
,用于显式覆盖基本虚函数。
C++11 introduced very useful specifier override
for explicitly override a base virtual function. But what about explicit hiding?
例如,考虑代码:
struct A: B {
void f();
}
- 如果有一个虚拟
void B :: f()
代码导致隐藏此函数。 - 如果存在非虚拟
void B :: f()
代码导致隐藏此函数。
- If there is a virtual
void B::f()
the code cause implicit overriding this function. - If there is a non-virtual
void B::f()
the code cause hiding this function.
b $ b
也就是说,代码的含义取决于 void B :: f()
的存在和虚拟性。
问题。如何显式隐藏基函数?我想得到错误,如果我试图隐藏虚拟功能。
Question. How to explicitly hide a base function? I want to get error if I try to hide virtual function.
如 override
是 guard ,以确保 / em>具有相同原型的虚拟基函数,我需要一个 guard 以确保没有具有相同原型的虚拟基函数。
Such as override
is the guard to ensure that there is virtual base function with the same prototype, I need a guard to ensure that there is no virtual base function with the same prototype.
Epic失败示例:
#include <stdio.h>
struct B {
void f() {printf("Hello\n");}
void g() {f();}
};
struct A: B {
void f() {g();}
};
int main() {
A a;
a.f();
return 0;
}
程序打印Hello。但如果我使 B :: f()
virtual程序导致分段错误(无限递归)。这可能是一个真正的问题,如果 B
类是第三方,我只是#include它,这是改变第三方代码的虚拟性可能会导致我的代码错误。
The program print "Hello". But if I make B::f()
virtual the program cause segmentation fault (infinite recursion). This may be a real problem if B
class is third-party and I just #include it, that is changing the virtuality in the third-party code may cause fault in my code.
UPD。我发现C#具有此功能通过新
说明符。
UPD. I found that C# have this feature via new
specifier. It's seems that C++ have not (yet?).
推荐答案
你可以使用什么来检查基类:
What you may use to check the base class :
// Class to check that B::f() is not virtual
// struct A requires that this class compiles, else struct A should epic fails.
struct checkInterfaceIsNotVirtual_B : B
{
void f() = delete;
};
如果 B :: f()
是虚拟的:
-
g ++:
g++:
error: deleted function 'virtual void checkInterfaceIsNotVirtual_B::f()'
clang ++:
clang++:
error: deleted function 'f' cannot override a non-deleted function
这篇关于在C ++中显式隐藏一个基函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!