c++类中的私有成员和受保护成员有什么区别?

我从最佳实践惯例中了解到,没有在类外部调用的变量和函数应该是私有的,但看看我的MFC项目,MFC似乎更倾向于受保护。

有什么区别,我应该用哪个?


当前回答

受保护的成员只能由类的后代和同一模块中的代码访问。私有成员只能被声明它们的类以及同一模块中的代码访问。

当然,朋友函数把这个扔出窗外,但是。

其他回答

Private =只能由母类(基类)访问 (只有我父母才能进我父母的卧室)

Protected =母类(基类)和她的子类可以访问 (只有父母可以进父母的卧室,但允许儿子/女儿进父母的卧室)

Public =母类(基类)、子类和其他所有人都可以访问 (只有我父母才能进我父母的卧室,但那是家庭聚会——我的家是我的家)

当然,看看受保护的成员变量问题。建议使用private作为默认值(就像c++类一样)来减少耦合。受保护的成员变量总是一个坏主意,受保护的成员函数可以用于例如模板方法模式。

c++类中的私有成员和受保护成员有什么区别?

其他的回答说:

公共-所有人都可以访问。 Protected -派生类(和友类)可以访问。 私人限制。

有什么区别,我应该用哪个?

c++的核心准则给出了数据应该始终是私有的建议。我认为这是一个很好的建议,因为当你的派生类可以访问受保护的数据时,它会导致“数据面条”。保护函数更有意义,但这取决于用例。

对于函数,你有一个选择。对于数据,应该将其设置为私有,并在需要时提供受保护的访问函数。这样可以更好地控制类数据。

The protected keyword specifies access to class members in the member-list up to the next access specifier (public or private) or the end of the class definition. Class members declared as protected can be used only by the following: Member functions of the class that originally declared these members. Friends of the class that originally declared these members. Classes derived with public or protected access from the class that originally declared these members. Direct privately derived classes that also have private access to protected members. When preceding the name of a base class, the protected keyword specifies that the public and protected members of the base class are protected members of its derived classes. Protected members are not as private as private members, which are accessible only to members of the class in which they are declared, but they are not as public as public members, which are accessible in any function. Protected members that are also declared as static are accessible to any friend or member function of a derived class. Protected members that are not declared as static are accessible to friends and member functions in a derived class only through a pointer to, reference to, or object of the derived class.

保护(c++)

a类的公共成员对所有人都是开放的。

类a的受保护成员不能在a的代码之外访问,但可以从派生自a的任何类的代码访问。

类a的私有成员不能在a的代码之外或从a派生的任何类的代码中访问。

因此,最终,在受保护还是私有之间做出选择是为了回答以下问题:您愿意对派生类的程序员给予多少信任?

默认情况下,假定派生类不可信,并将成员设为private。如果你有一个很好的理由让它的派生类可以自由访问母类的内部内容,那么你可以让它们受到保护。