私有成员和受保护成员:C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/224966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:51:32  来源:igfitidea点击:

Private and Protected Members : C++

c++classmfc

提问by Konrad

Can someone enlighten me as to the difference between privateand protectedmembers in classes?

有人可以启发我了解班级成员privateprotected成员之间的区别吗?

I understand from best practice conventions that variables and functions which are not called outside the class should be made private- but looking at my MFCproject, MFCseems to favor protected.

我从最佳实践约定中了解到,应该创建不在类外部调用的变量和函数private- 但看看我的MFC项目,MFC似乎更喜欢protected.

What's the difference and which should I use?

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

回答by Firas Assaad

Private members are only accessible within the class defining them.

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

Protected members are accessible in the class that defines them and in classes that inherit from that class.

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

Edit: Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes.

编辑:它们的类的朋友也可以访问它们,在受保护成员的情况下,它们的派生类的朋友也可以访问它们。

Edit 2: Use whatever makes sense in the context of your problem. You should try to make members private whenever you can to reduce coupling and protect the implementation of the base class, but if that's not possible then use protected members. Check C++ FAQfor a better understanding of the issue. This question about protected variablesmight also help.

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

回答by paercebal

Publicmembers of a class A are accessible for all and everyone.

A 类的公共成员可供所有人访问。

Protectedmembers of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A.

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

Privatemembers of a class A are not accessible outside of A's code, or from the code of any class derived from A.

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

So, in the end, choosing between protected or private is answering the following questions: How much trust are you willing to put into the programmer of the derived class?

因此,最终,在受保护或私有之间进行选择是在回答以下问题:您愿意对派生类的程序员信任多少?

By default, assume the derived class is not to be trusted, and make your members private. If you have a very good reason to give free access of the mother class' internals to its derived classes, then you can make them protected.

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

回答by Roddy

Protected members can be accessed from derived classes. Private ones can't.

可以从派生类访问受保护的成员。私人的不能。

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
};

In terms of "best practice", it depends. If there's even a faint possibility that someone might want to derive a new class from your existing one and need access to internal members, make them Protected, not Private. If they're private, your class may become difficult to inherit from easily.

在“最佳实践”方面,这取决于。如果有人可能想要从您现有的类派生一个新类并需要访问内部成员的可能性很小,请将它们设为 Protected,而不是 Private。如果它们是私有的,您的类可能会变得难以轻松继承。

回答by Toon Krijthe

The reason that MFC favors protected, is because it is a framework. You probably want to subclass the MFC classes and in that case a protected interface is needed to access methods that are not visible to general use of the class.

MFC 之所以偏爱受保护,是因为它是一个框架。您可能希望对 MFC 类进行子类化,在这种情况下,需要一个受保护的接口来访问对类的一般使用不可见的方法。

回答by Mats Fredriksson

It all depends on what you want to do, and what you want the derived classes to be able to see.

这完全取决于您想要做什么,以及您希望派生类能够看到什么。

class A
{
private:
    int _privInt = 0;
    int privFunc(){return 0;}
    virtual int privVirtFunc(){return 0;}
protected:
    int _protInt = 0;
    int protFunc(){return 0;}
public:
    int _publInt = 0;
    int publFunc()
    {
         return privVirtFunc();
    }
};

class B : public A
{
private:
    virtual int privVirtFunc(){return 1;}
public:
    void func()
    {
        _privInt = 1; // wont work
        _protInt = 1; // will work
        _publInt = 1; // will work
        privFunc(); // wont work
        privVirtFunc(); // wont work
        protFunc(); // will work
        publFunc(); // will return 1 since it's overridden in this class
    }
}

回答by xtofl

Sure take a look at the Protected Member Variablesquestion. It is recommended to use private as a default (just like C++ classses do) to reduce coupling. Protected member variables are most always a bad idea, protected member functions can be used for e.g. the Template Method pattern.

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

回答by fhe

Attributes and methods marked as protectedare -- unlike private ones -- still visible in subclasses.

标记为的属性和方法protected——与私有的不同——在子类中仍然可见。

Unless you don't want to use or provide the possibility to override the method in possible subclasses, I'd make them private.

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

回答by Ignacio Vazquez-Abrams

Protected members can only be accessed by descendants of the class, and by code in the same module. Private members can only be accessed by the class they're declared in, and by code in the same module.

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

Of course friend functions throw this out the window, but oh well.

当然,友元函数会将其抛之脑后,但哦,好吧。

回答by PhilGriffin

private members are only accessible from within the class, protected members are accessible in the class and derived classes. It's a feature of inheritance in OO languages.

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

You can have private, protected and public inheritance in C++, which will determine what derived classes can access in the inheritance hierarchy. C# for example only has public inheritance.

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

回答by Johan K. Rhodes

private= accessible by the mothership (base class) only (ie only my parent can go into my parent's bedroom)

private= 只能由母舰(基类)访问(即只有我的父母可以进入我父母的卧室)

protected= accessible by mothership (base class), and her daughters (ie only my parent can go into my parent's bedroom, but gave son/daughter permission to walk into parent's bedroom)

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

public= accessible by mothership (base class), daughter, and everyone else (ie only my parent can go into my parent's bedroom, but it's a house party - mi casa su casa)

public= 母舰(基类)、女儿和其他所有人都可以访问(即只有我的父母可以进入我父母的卧室,但这是一个家庭聚会 - mi casa su casa)