是否总是邪恶有方法的结构? [英] Is it always evil to have a struct with methods?

查看:158
本文介绍了是否总是邪恶有方法的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚浏览过并发现了以下内容:



p>共识是,按照惯例,你应该只使用结构的POD,没有方法等。



我一直觉得一些类型是自然结构而不是类,但仍然可以有几个帮助函数作为成员。结构体应该仍然是大多数通常的规则的POD - 特别是它必须是安全的复制使用memcpy。必须公开所有成员资料。但是我仍然有意义的是帮助函数作为成员。我甚至不会反对私人的方法,虽然我不记得自己这样做。虽然它打破了正常的POD规则,但我不会反对一个具有构造函数的结构,只要它们只是初始化一个几个字段的构造函数(重写赋值或析构函数肯定会违反规则)。



对我来说,结构体直观上是一个字段的集合 - 一个数据结构节点或者什么 - 而一个类是一个抽象。



我甚至认为我曾经读过一次。



这是否符合公认的最佳做法?



EDIT - POD(普通旧数据)被此问题误导。特别地,结构体可以是非POD,纯粹是因为成员是非POD - 例如。具有类型为std :: string的成员的聚合。该聚合不能与memcpy一起复制。如有混淆,请参阅此处

解决方案

对于有价值的,所有的标准STL函数都被定义为结构体,它们的唯一目的是具有成员函数; STL函数不应该有状态。



编辑:个人来说,每当一个类全部使用时,我使用 struct 公共成员。它不重要,只要一个是一致的。


I've just been browsing and spotted the following...

When should you use a class vs a struct in C++?

The consensus there is that, by convention, you should only use struct for POD, no methods, etc.

I've always felt that some types were naturally structs rather than classes, yet could still have a few helper functions as members. The struct should still be POD by most of the usual rules - in particular it must be safe to copy using memcpy. It must have all member data public. But it still makes sense to me to have helper functions as members. I wouldn't even necessarily object to a private method, though I don't recall ever doing this myself. And although it breaks the normal POD rules, I wouldn't object to a struct having constructors, provided they were just initialise-a-few-fields constructors (overriding assignment or destructors would definitely be against the rules).

To me a struct is intuitively a collection of fields - a data structure node or whatever - whereas a class is an abstraction. The logical place to put the helper functions for your collection-of-fields may well be within the struct.

I even think I once read some advice along these lines, though I don't remember where.

Is this against accepted best practice?

EDIT - POD (Plain Old Data) is misrepresented by this question. In particular, a struct can be non-POD purely because a member is non-POD - e.g. an aggregate with a member of type std::string. That aggregate must not be copied with memcpy. In case of confusion, see here.

解决方案

For what it's worth, all the standard STL functors are defined as structs, and their sole purpose is to have member functions; STL functors aren't supposed to have state.

EDIT: Personally, I use struct whenever a class has all public members. It matters little, so long as one is consistent.

这篇关于是否总是邪恶有方法的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆