在C++中使虚拟函数私有化

Making virtual function private in C++

本文关键字:函数 私有化 虚拟 C++      更新时间:2023-10-16
class A 
{
public:
virtual void fun() 
{ 
cout << "A Fun"; 
}
};
class B:public A
{
private:
void fun() 
{ 
cout << "B Fun"; 
}
};
class C:public B{};
int main()
{
//Case1       
A *ptr = new C();
ptr->fun();
/*
OUTPUT : B Fun
*/
//Case 2
B *ptr2 = new C();
ptr2->fun();
/*
ERROR:
main.cpp: In function ‘int main()’:
error: ‘virtual void B::fun()’ is private within this context
ptr2->fun();
^
note: declared private here
void fun()
^~~ 
*/
return 0;
}

在情况1中:我可以调用类B中的私有fun((,但为什么在情况2中我不能调用私有fun?为什么B类中的fun((有两种不同的行为?我的意思是说,当我使A类型的指针时,类B的fun((充当公共函数,但当我使B类型的指针,则类B的fun((充当私有函数。

在情况1中:我可以调用B类中的私有函数((〔…〕

不,您不能调用类B中的private方法。您正在调用类A中的public方法,该方法恰好在子类中被覆盖。

这在单元测试私有方法时尤其有用。您只需让您的类从一个伪基类继承,该伪基类将感兴趣的方法声明为public和(可能是纯的(virtual

私有性和公共性是类/结构成员的纯编译时属性。编译器在编译代码时检查您是否有权访问成员。

所以在你的代码中:

B b;
b.fun(); // Error! B::fun is private in this context!
A& a = static_cast<A&>(b); // `a` is a reference to `b`
a.fun(); // okay, A::fun is public.
// It just so happen that A::fun is virtual,
// So the function dispatched at runtime will be B::fun
// But the compiler has no mean to check this.

如果函数已被重写,并且仅当函数A::fun是虚拟的,则确定运行时的行为。通过重写虚拟函数,必须同意使用A的表达式将被调度到B,而不管B上有什么限制。以多态方式调用A::fun的代码必须与任何子类一起工作,因为处理基类的代码无法知道派生类。