c++类中的私有成员和受保护成员有什么区别?
我从最佳实践惯例中了解到,没有在类外部调用的变量和函数应该是私有的,但看看我的MFC项目,MFC似乎更倾向于受保护。
有什么区别,我应该用哪个?
c++类中的私有成员和受保护成员有什么区别?
我从最佳实践惯例中了解到,没有在类外部调用的变量和函数应该是私有的,但看看我的MFC项目,MFC似乎更倾向于受保护。
有什么区别,我应该用哪个?
当前回答
私有成员只能在定义它们的类中访问。
可在定义受保护成员的类中以及从该类继承的类中访问受保护成员。
编辑:两者都可以被其类的友元访问,如果是受保护成员,则可以被其派生类的友元访问。
编辑2:使用任何在你的问题上下文中有意义的东西。您应该尽可能地将成员设为private,以减少耦合并保护基类的实现,但如果不可能,则使用受保护的成员。查看c++常见问题以更好地理解这个问题。这个关于受保护变量的问题可能也有帮助。
其他回答
私有成员只能在定义它们的类中访问。
可在定义受保护成员的类中以及从该类继承的类中访问受保护成员。
编辑:两者都可以被其类的友元访问,如果是受保护成员,则可以被其派生类的友元访问。
编辑2:使用任何在你的问题上下文中有意义的东西。您应该尽可能地将成员设为private,以减少耦合并保护基类的实现,但如果不可能,则使用受保护的成员。查看c++常见问题以更好地理解这个问题。这个关于受保护变量的问题可能也有帮助。
与私有属性和方法不同,标记为受保护的属性和方法在子类中仍然可见。
除非您不想在可能的子类中使用或提供重写该方法的可能性,否则我会将它们设为private。
私有访问修饰符和受保护访问修饰符是相同的,只是基类的受保护成员可以在子(派生)类的基类范围之外被访问。 它也同样适用于继承。 但是使用私有修饰符,基类的成员只能在基类的作用域或代码中访问,它的友函数只能是''''
由于不需要公共成员函数来获取和更新派生类中的受保护成员,这提高了代码的效率,并减少了需要编写的代码量。然而,派生类的程序员应该知道他在做什么。
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++)