简体   繁体   English

类中的默认安全性参数

[英]Default security parameter in classes

I have noticed in a large amount of code that people declare their classes public before writing code into it. 我已经在大量的代码的人宣称他们发现classes public编写代码到它。 Is this a preference or is there more meaning to it? 这是偏好还是有更多意义? It seems kind of superfluous to me being that struct's default parameter is public and does exactly what a class does (as I have read) . 对于我而言, struct's默认参数是public并且正如类所做的那样(正如我所读到的),这似乎是多余的。

code example 代码示例

class box
{
public:
void setParam( int x, int y) { . . . }
int getWidth(){ . . . }
int getHeight(){ . . . }
private:
int width, height;
}

Could be done without declaring it public in a struct. 可以在没有在结构中声明它公开的情况下完成。

Generally its a matter of convention/semantics than it is because of a technical reason. 一般来说,它是一个约定/语义问题,而不是因为技术原因。

The rationale is usually that struct s are reserved for POD usage, helper data structures, "data payload"s, functors etc. Whereas class es are for types that encapsulate non-trivial operations that usually have to respect some type of class invariant. 基本原理通常是struct被保留用于POD使用,辅助数据结构,“数据有效载荷”,仿函数等。而class es用于封装非平凡操作的类型,通常必须遵守某些类型的类不变量。

A struct that looks like your class might look like this: 一个struct ,看起来像你的类可能是这样的:

struct Rect
{
 int x, y, w, h;
};

It instantly conveys to the reader that it's intended to be an simple POD type with no bells and whistles. 它立即传达给读者它的目的是一个简单的POD类型,没有铃声和口哨声。 On the other hand, your example has accessor methods which seem superfluous if all they intend to do is get and set your private members. 另一方面,您的示例具有访问器方法,如果他们打算做的只是获取并设置您的私有成员,这些方法似乎是多余的。 You might as well make them public. 你也可以将它们公之于众。


Example of my comment: 我的评论示例:

class box
{
  Rect _surface;
public:
  explicit box(Rect surface) : _surface(surface)
  {
    if (surface.w <= 0 || surface.h <= 0) throw bad_dimensions();
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM