c++类中的私有成员和受保护成员有什么区别?
我从最佳实践惯例中了解到,没有在类外部调用的变量和函数应该是私有的,但看看我的MFC项目,MFC似乎更倾向于受保护。
有什么区别,我应该用哪个?
c++类中的私有成员和受保护成员有什么区别?
我从最佳实践惯例中了解到,没有在类外部调用的变量和函数应该是私有的,但看看我的MFC项目,MFC似乎更倾向于受保护。
有什么区别,我应该用哪个?
当前回答
私有成员只能从类内部访问,受保护成员可以在类和派生类中访问。这是面向对象语言中继承的一个特性。
在c++中可以有私有、受保护和公共继承,这将决定哪些派生类可以在继承层次结构中访问。例如,c#只有公共继承。
其他回答
私有成员只能在声明它的类中访问,而受保护成员可以在声明它的类中与它继承的类一起访问。
Private =只能由母类(基类)访问 (只有我父母才能进我父母的卧室)
Protected =母类(基类)和她的子类可以访问 (只有父母可以进父母的卧室,但允许儿子/女儿进父母的卧室)
Public =母类(基类)、子类和其他所有人都可以访问 (只有我父母才能进我父母的卧室,但那是家庭聚会——我的家是我的家)
私有访问修饰符和受保护访问修饰符是相同的,只是基类的受保护成员可以在子(派生)类的基类范围之外被访问。 它也同样适用于继承。 但是使用私有修饰符,基类的成员只能在基类的作用域或代码中访问,它的友函数只能是''''
Private: It is an access specifier. By default the instance (member) variables or the methods of a class in c++/java are private. During inheritance, the code and the data are always inherited but is not accessible outside the class. We can declare our data members as private so that no one can make direct changes to our member variables and we can provide public getters and setters in order to change our private members. And this concept is always applied in the business rule. Protected: It is also an access specifier. In C++, the protected members are accessible within the class and to the inherited class but not outside the class. In Java, the protected members are accessible within the class, to the inherited class as well as to all the classes within the same package.
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++)