Last Updated: 2023-12-23 12:04:53 Saturday
-- TOC --
C++中的public,protected和private这三个关键词,既可以用来修饰类成员,表达成员的可访问性;也可以用来在继承的时候修饰基类,表达继承关系。
看到有人这样总结:类的封装特性由public和private体现,而继承特性由protected来呈现!
规则:
继承时,这3个关键词的含义变化:
继承方式 | public | protected |
---|---|---|
public | public | protected |
protected | protected | protected |
private | private | private |
class默认是private,成员和继承如果不加修饰,默认都是private!
struct默认是public,成员和继承如果不加修饰,默认都是public!(struct继承class,默认也是public)
声明为 private 的成员和声明为 public 的成员的顺序是任意的,既可以先出现 private 部分,也可以先出现 public 部分。
public成员变量可以带来访问的便利和更快的访问速度。
Member Inheritance
Derived classes inherit non-private members from their base classes. Classes can use inherited members just like normal members. The supposed benefit of member inheritance is that you can define functionality once in a base class and not have to repeat it in the derived classes. Unfortunately, experience has convinced many in the programming community to avoid member inheritance because it can easily yield brittle, hard-to-reason-about code compared to composition-based polymorphism. (This is why so many modern programming languages exclude it.)
所谓composition-based polymorphism,就是在某个class中,直接用其它class对象来作为成员。上面这段文字在说,很多人认为这种方式,比member inheritance要好。
外部访问private成员
本文链接:https://cs.pynote.net/sf/c/cpp/202205062/
-- EOF --
-- MORE --