C++ 访问继承中的私有成员

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8241462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:14:55  来源:igfitidea点击:

access private members in inheritance

c++inheritanceprivate

提问by ofer

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 类,它有一个字段 val 声明为私有。我想声明一个类 B,它继承自 A 并可以访问 val。有没有办法在 C++ 上做到这一点?

I want to do it because I need to overload some functions of A, without changing A code at all.

我想这样做是因为我需要重载A的一些功能,而根本不改变A代码。

Thanks.

谢谢。

回答by Constantinius

Quick answer: You don't. Thats what the protectedkey-word is for, which you want to use if you want to grant access to subclasses but no-one else.

快速回答:你没有。这就是protected关键字的用途,如果您想授予对子类的访问权而不是其他人,则要使用该关键字。

privatemeans that no-one has access to those variables, not even subclasses.

private意味着没有人可以访问这些变量,甚至不能访问子类。

If you cannot change code in Aat all, maybe there is a public/protectedaccess 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!).

如果您根本无法更改代码A,则该变量可能有public/protected访问方法。否则这些变量不能从子类访问,只有 hacks 可以提供帮助(我不鼓励!)。

回答by Schehaider Aymen

Private members of a base classcan only be accessed by base member functions (not derived classes). So you have no rights not even a chance to do so :)

基类的私有成员只能被基成员函数访问(不能被派生类访问)。所以你没有权利甚至没有机会这样做:)

class Base

class Base

  • public: can be accessed by anybody
  • private: can only be accessed by only base member functions (not derived classes)
  • protected: can be accessed by both base member functions and derived classes
  • public: 任何人都可以访问
  • private:只能被基成员函数访问(不能被派生类访问)
  • protected: 可以被基成员函数和派生类访问

回答by dbrank0

Well, if you have access to base class, you can declare class B as friend class. But as others explained it: because you can, it does not mean it's good idea. Use protected members, if you want derived classes to be able to access them.

好吧,如果您有权访问基类,则可以将 B声明为友元类。但正如其他人所解释的那样:因为你可以,这并不意味着这是个好主意。如果您希望派生类能够访问它们,请使用受保护的成员。

回答by Eoin

It is doable as describe in this Guru of the Week - GotW #76 - Uses and Abuses of Access Rights. But it's should be considered a last resort.

正如本周 Guru - GotW #76 - 访问权限的使用和滥用中所述,这是可行的。但它应该被认为是最后的手段。

回答by Meysam

You need to define it as protected. Protected members are inherited to child classes but are not accessible from the outside world.

您需要将其定义为protected. 受保护的成员继承给子类,但不能从外部访问。