C++ 的私有成员和受保护成员之间有什么区别? 课程?

发布于 2024-07-06 22:49:30 字数 190 浏览 9 评论 0原文

C++ 类中的 privateprotected 成员有什么区别?

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

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

What is the difference between private and protected members in C++ classes?

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 MFC project, MFC seems to favor protected.

What's the difference and which should I use?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

白云不回头 2024-07-13 22:49:30

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

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

它们的类的友元也可以访问它们,如果是受保护的成员,则可以由其派生类的友元访问。

使用任何对您的问题有意义的内容。 您应该尽可能将成员设为私有,以减少耦合并保护基类的实现,但如果不可能,则使用受保护的成员。

查看C++ 常见问题解答以更好地了解该问题。 这个有关受保护变量的问题可能也会有帮助。

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.

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

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++ FAQ for a better understanding of the issue. This question about protected variables might also help.

嘦怹 2024-07-13 22:49:30

A 类的公共成员可供所有人使用。

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

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

因此,最终,在 protected 或 private 之间进行选择将回答以下问题:您愿意对派生类的程序员给予多少信任

默认情况下,假设派生类不可信,并将您的成员设置为私有。 如果您有充分的理由允许其派生类自由访问母类的内部结构,那么您可以将它们设置为受保护的。

Public members of a class A are accessible for all and everyone.

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

Private members of a class A are not accessible outside of A's code, or from the code of any class derived from 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.

云朵有点甜 2024-07-13 22:49:30

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

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 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.

落花浅忆 2024-07-13 22:49:30

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

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.

风流物 2024-07-13 22:49:30

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

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(); // will work, simply calls the derived version.
        protFunc(); // will work
        publFunc(); // will return 1 since it's overridden in this class
    }
}

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(); // will work, simply calls the derived version.
        protFunc(); // will work
        publFunc(); // will return 1 since it's overridden in this class
    }
}
不醒的梦 2024-07-13 22:49:30

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

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

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

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

明月松间行 2024-07-13 22:49:30

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

Sure take a look at the Protected Member Variables question. 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.

默嘫て 2024-07-13 22:49:30

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

当然,友元函数将其排除在外,但是哦,好吧。

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.

岁月静好 2024-07-13 22:49:30

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

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

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.

明月松间行 2024-07-13 22:49:30

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

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

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

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

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)

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)

我的影子我的梦 2024-07-13 22:49:30

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

Since no public member function is needed to fetch and update protected members in the derived class, this increases the efficiency of code and reduces the amount of code we need to write. However, programmer of the derived class is supposed to be aware of what he is doing.

不即不离 2024-07-13 22:49:30

对于成员数据,首选 private。 默认情况下,C++ 类中的成员是私有

public 是成员函数的首选,尽管这是一个意见问题。 至少某些方法必须是可访问的。 public 可供所有人访问。 这是最灵活的选择,也是最不安全的选择。 任何人都可以使用它们,任何人都可以滥用它们。

private 根本无法访问。 没有人可以在课堂之外使用它们,也没有人可以滥用它们。 即使在派生类中也不行。

protected 是一种折衷方案,因为它可以在派生类中使用。 当您从一个类派生时,您对基类有很好的了解,并且您会小心不要误用这些成员。

MFC 是 Windows API 的 C++ 包装器,它更喜欢 publicprotected。 由 Visual Studio 向导生成的类具有丑陋的 protectedpublicprivate 成员组合。 但 MFC 类本身有一些逻辑。

SetWindowText 等成员是 public,因为您经常需要访问这些成员。

OnLButtonDown 等成员处理窗口接收到的通知。 它们不应该被访问,因此它们受到保护。 您仍然可以在派生类中访问它们以重写这些函数。

有些成员必须执行线程和消息循环,它们不应该被访问或覆盖,因此它们被声明为 private

在 C++ 结构中,成员默认为 public。 结构通常仅用于数据,而不用于方法,因此 public 声明被认为是安全的。

private is preferred for member data. Members in C++ classes are private by default.

public is preferred for member functions, though it is a matter of opinion. At least some methods must be accessible. public is accessible to all. It is the most flexible option and least safe. Anybody can use them, and anybody can misuse them.

private is not accessible at all. Nobody can use them outside the class, and nobody can misuse them. Not even in derived classes.

protected is a compromise because it can be used in derived classes. When you derive from a class, you have a good understanding of the base class, and you are careful not to misuse these members.

MFC is a C++ wrapper for Windows API, it prefers public and protected. Classes generated by Visual Studio wizard have an ugly mix of protected, public, and private members. But there is some logic to MFC classes themselves.

Members such as SetWindowText are public because you often need to access these members.

Members such as OnLButtonDown, handle notifications received by the window. They should not be accessed, therefore they are protected. You can still access them in the derived class to override these functions.

Some members have to do threads and message loops, they should not be accessed or override, so they are declared as private

In C++ structures, members are public by default. Structures are usually used for data only, not methods, therefore public declaration is considered safe.

债姬 2024-07-13 22:49:30

私有:可由类成员函数访问 友元函数或友元类。
对于 C++ 类,这是默认访问说明符。

受保护:可通过类成员函数、友元函数或友元类和类访问。 派生类。

  • 您可以根据您的要求将类成员变量或函数(甚至 typedef 或内部类)保留为私有或受保护。
  • 大多数时候,您将类成员保留为私有成员,并添加 get/set 函数进行封装。 这有助于代码的维护。
  • 通常,当您想要保持公共函数模块化或消除重复代码而不是将整个代码写入单个函数时,请使用私有函数。 这有助于代码的维护。

请参阅此链接了解更多详细信息。

Private : Accessible by class member functions & friend function or friend class.
For C++ class this is default access specifier.

Protected: Accessible by class member functions, friend function or friend class & derived classes.

  • You can keep class member variable or function (even typedefs or inner classes) as private or protected as per your requirement.
  • Most of the time you keep class member as a private and add get/set functions to encapsulate. This helps in maintenance of code.
  • Generally private function is used when you want to keep your public functions modular or to eliminate repeated code instead of writing whole code in to single function. This helps in maintenance of code.

Refer this link for more detail.

︶ ̄淡然 2024-07-13 22:49:30
  • 私有:它是一个访问说明符。 默认情况下,c++/java 中类的实例(成员)变量或方法是私有的。 在继承期间,代码和数据始终被继承,但在类外部不可访问。 我们可以将数据成员声明为私有成员,这样就没有人可以直接更改我们的成员变量,并且我们可以提供公共 getter 和 setter 来更改我们的私有成员。 并且这个概念总是应用在业务规则中。

  • 受保护:它也是一个访问说明符。 在 C++ 中,受保护的成员可以在类内部和继承类中访问,但不能在类外部访问。 在Java中,受保护的成员可以在类内、继承的类以及同一包中的所有类中访问。

  • 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.

后来的我们 2024-07-13 22:49:30

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

Private member can be accessed only in same class where it has declared where as protected member can be accessed in class where it is declared along with the classes which are inherited by it .

只有影子陪我不离不弃 2024-07-13 22:49:30

受保护的非静态基类成员可以由从该基类派生的任何类的成员和友元通过使用下列之一来访问:

  • 指向直接或间接派生类
  • 的指针 对直接或间接派生类的引用
  • 一个对象直接或间接派生类

A protected nonstatic base class member can be accessed by members and friends of any classes derived from that base class by using one of the following:

  • A pointer to a directly or indirectly derived class
  • A reference to a directly or indirectly derived class
  • An object of a directly or indirectly derived class
流殇 2024-07-13 22:49:30

protected 关键字指定对类成员的访问
成员列表到下一个访问说明符(publicprivate)或
类定义结束。 声明为 protected类成员可以
只能由以下人员使用:

  • 最初声明这些成员的类的成员函数。
  • 最初声明这些成员的类的友元。
  • 从最初声明这些成员的类派生出具有公共或受保护访问权限的类。
  • 直接私有派生类也可以私有访问受保护的成员。

当基类名称前面时,protected 关键字
指定基类的公共和受保护成员是
其派生类的受保护成员。

受保护的成员不像 private 成员那样私有,后者是
仅可由声明它们的类的成员访问,
但它们不像公共成员那样公开,可以在
任何功能。

也声明为静态的受保护成员可以访问
派生类的任何友元或成员函数。 受保护会员
未声明为静态的内容可供朋友和会员访问
派生类中的函数只能通过指针、引用、
或派生类的对象。

受保护 (C++)

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.

protected (C++)

如梦初醒的夏天 2024-07-13 22:49:30

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

其他答案指出:

  • 公开 - 所有人都可以访问。
  • protected - 可由派生类(和朋友)访问。
  • 私人-受限。

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

C++ 核心指南建议数据应始终是私有的。 我认为这是一个很好的建议,因为当您拥有可以访问受保护数据的派生类时,它会导致“数据意大利面条”。 保护功能更有意义,但这取决于用例。

对于功能,您可以选择。 对于数据,您应该将其设为私有,并在需要时提供受保护的访问器函数。 这可以更好地控制类数据。

What is the difference between private and protected members in C++ classes?

Other answers have stated:

  • public - accessible by all.
  • protected - accessible by derived classes (and friends).
  • private - restricted.

What's the difference and which should I use?

The C++ core guidelines gives the advice that data should always be private. I think this is good advice as it makes for 'data spaghetti' when you have derived classes that can access protected data. It makes much more sense for functions to be protected, but it depends on the use case.

For functions you have a choice. For data, you should make it private and provide protected accessor functions if needed. This gives more control over the class data.

转瞬即逝 2024-07-13 22:49:30

private 和 protected 访问修饰符是一回事,只是基类的受保护成员可以在子(派生)类中的基类范围之外访问。
这也同样适用于继承。
但是使用 private 修饰符,基类的成员只能在基类及其友元函数的范围或代码中访问''''

private and protected access modifiers are one and same only that protected members of the base class can be accessed outside the scope of the base class in the child(derived)class.
It also applies the same to inheritance .
But with the private modifier the members of the base class can only be accessed in the scope or code of the base class and its friend functions only''''

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文