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

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

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


当前回答

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.

其他回答

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

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.

与私有属性和方法不同,标记为受保护的属性和方法在子类中仍然可见。

除非您不想在可能的子类中使用或提供重写该方法的可能性,否则我会将它们设为private。

私有成员只能从类内部访问,受保护成员可以在类和派生类中访问。这是面向对象语言中继承的一个特性。

在c++中可以有私有、受保护和公共继承,这将决定哪些派生类可以在继承层次结构中访问。例如,c#只有公共继承。

MFC偏爱protected的原因是因为它是一个框架。您可能想要子类化MFC类,在这种情况下,需要一个受保护的接口来访问类的一般用途不可见的方法。