C++ 私有结构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8454622/
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-28 18:35:52  来源:igfitidea点击:

C++ Private Structures

c++structstructureprivate-members

提问by Dasaru

I have read that the main differences between classes and structures (other than functions), is that class members default to private, whereas structure members default to public.

我读过类和结构(函数除外)之间的主要区别在于,类成员默认为私有,而结构成员默认为公有。

That implies that structure members can be private. My question is: Can you have private structure members? And if you can, what is the purpose of using private members? How would you even access them?

这意味着结构成员可以是私有的。我的问题是:您可以拥有私有结构成员吗?如果可以,使用私有成员的目的是什么?你甚至会如何访问它们?

回答by Alok Save

Yes structures can have private members, you just need to use the access specifier for the same.

是的结构可以有私有成员,您只需要使用相同的访问说明符。

struct Mystruct
{
    private:
       m_data;

};

Only difference between structure and class are:

结构和类之间的唯一区别是:

  • access specifier defaults to private for class and public for struct
  • inheritance defaults to private for class and public for struct
  • 访问说明符默认为私有的类和公共的结构
  • 继承默认为私有的类和公共的结构

How can you access them?
Just like you access private members of a class. i.e: they can only be accessed within the structures member functions and not in derived structure etc.

您如何访问它们?
就像您访问类的私有成员一样。即:它们只能在结构成员函数中访问,而不能在派生结构等中访问。

回答by bdonlan

The onlydifference between structand classis default access (with the exception of some weird template situations, see Alf's comments below). This means you can access private members in the same way as in a class:

和之间的唯一区别是默认访问(除了一些奇怪的模板情况,请参阅下面的 Alf 评论)。这意味着您可以像在类中一样访问私有成员:structclass

struct foo {
  int get_X() { return x; }
  void set_X(int x_) { x = x_; }
private:
  int x;
};

Whether you use structor class, then, is purely a matter of style. I tend to use structwhen all members are public (eg, if it's a functor class with no member variables and only public functions).

那么,您是否使用structclass纯粹是风格问题。我倾向于struct在所有成员都是公共成员时使用(例如,如果它是一个没有成员变量而只有公共函数的函子类)。

回答by Peter Addy

One thing that makes this useful is that you can also use the friend key word in structs, so private members can only be used and modified by those specific functions or classes or what not that you want to be able to modify it. This way the user can't modify those sections themselves. They won't even show up in the auto fill features, at least in visual studio.

使这有用的一件事是您还可以在结构中使用朋友关键字,因此私有成员只能由那些特定的函数或类或您不希望能够对其进行修改的内容使用和修改。这样用户就不能自己修改这些部分。它们甚至不会出现在自动填充功能中,至少在 Visual Studio 中是这样。