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

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

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


当前回答

可以从派生类访问受保护的成员。私立学校则不行。

class Base {

private: 
  int MyPrivateInt;
protected: 
  int MyProtectedInt;
public:
  int MyPublicInt;
};

class Derived : Base
{
public:
  int foo1()  { return MyPrivateInt;} // Won't compile!
  int foo2()  { return MyProtectedInt;} // OK  
  int foo3()  { return MyPublicInt;} // OK
};‌‌

class Unrelated 
{
private:
  Base B;
public:
  int foo1()  { return B.MyPrivateInt;} // Won't compile!
  int foo2()  { return B.MyProtectedInt;} // Won't compile
  int foo3()  { return B.MyPublicInt;} // OK
};

至于“最佳实践”,则视情况而定。如果有人想要从您现有的类中派生一个新类,并且需要访问内部成员,那么将它们设置为Protected,而不是Private。如果它们是私有的,那么您的类就很难轻易继承。

其他回答

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.

私有成员只能在声明它的类中访问,而受保护成员可以在声明它的类中与它继承的类一起访问。

私有成员只能在定义它们的类中访问。

可在定义受保护成员的类中以及从该类继承的类中访问受保护成员。

编辑:两者都可以被其类的友元访问,如果是受保护成员,则可以被其派生类的友元访问。

编辑2:使用任何在你的问题上下文中有意义的东西。您应该尽可能地将成员设为private,以减少耦合并保护基类的实现,但如果不可能,则使用受保护的成员。查看c++常见问题以更好地理解这个问题。这个关于受保护变量的问题可能也有帮助。

由于不需要公共成员函数来获取和更新派生类中的受保护成员,这提高了代码的效率,并减少了需要编写的代码量。然而,派生类的程序员应该知道他在做什么。

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

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