问题描述
我有一个A类,它有一个声明为private的字段val。
我想声明一个B类,它继承自A并且可以访问val。
有没有办法在C ++上实现?
I have a class A, which have a field val declared as private.I want to declare a class B, that inherit from A and have an access to val.Is there a way to do it on C++?
我想这样做是因为我需要重载A的一些函数,而根本不需要更改A代码。
I want to do it because I need to overload some functions of A, without changing A code at all.
谢谢。
推荐答案
快速回答:你没有。这是 protected
关键字的用途,如果你想授予对子类的访问权限,你想要使用它,而不是其他人。
Quick answer: You don't. Thats what the protected
key-word is for, which you want to use if you want to grant access to subclasses but no-one else.
private
表示没有人可以访问这些变量,甚至没有子类。
private
means that no-one has access to those variables, not even subclasses.
如果您根本无法更改 A
中的代码,可能会有 public
/ protected
该变量的访问方法。否则这些变量不能从子类访问,只有黑客可以帮助(我不鼓励!)。
If you cannot change code in A
at all, maybe there is a public
/protected
access method for that variable. Otherwise these variables are not meant to be accessed from subclasses and only hacks can help (which I don't encourage!).
这篇关于访问继承中的私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!