在C++中使虚拟函数私有化
Making virtual function private in C++
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
的代码必须与任何子类一起工作,因为处理基类的代码无法知道派生类。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中使虚拟函数私有化