C++ 受保护和私有有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12784083/
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-27 16:37:06  来源:igfitidea点击:

What is the difference between protected and private?

c++oopclassprivateprotected

提问by danijar

Possible Duplicate:
Private and Protected Members : C++

可能重复:
私有成员和受保护成员:C++

I don't understand the difference between protected and private members or methods, as I assumed both will hide the member or the function to access from outside the class.

我不明白受保护和私有成员或方法之间的区别,因为我认为两者都会隐藏要从类外部访问的成员或函数。

What is the difference between the protected and the private keywords?

protected 和 private 关键字有什么区别?

回答by dsgriffin

private- only available to be accessed within the class that defines them.

private- 只能在定义它们的类中访问。

protected- accessible in the class that defines them and in other classes which inherit from that class.

protected- 在定义它们的类和从该类继承的其他类中可访问。

回答by Jesper

Things that are privateare only visible within the class itself.

private仅在类本身内可见的事物。

Things that are protectedare visible in the class itself and in subclasses.

protected在类本身和子类中可见的事物。

回答by akrabi

The difference is who can access those functions.

不同之处在于谁可以访问这些功能。

  • Private= only members of the same class can access the function.

  • Protected= Same as private but derived classes can also access.

  • Private= 只有同一类的成员才能访问该函数。

  • Protected= 与私有相同,但派生类也可以访问。

回答by Fabio

Private methods are usually visible to class instances (internal implementations), protected methods are visible to subclasses and classes in the same package (inheritance and restricted usage).

私有方法通常对类实例(内部实现)可见,受保护方法对同一包中的子类和类可见(继承和限制使用)。

回答by b3h3m0th

Private members can only be used by that classes members and its friends; protected members can be inherited by other classes, and can be used by the classes members and friends.

私有成员只能被该类成员及其朋友使用;protected 成员可以被其他类继承,并且可以被类成员和朋友使用。