Structs与C ++中的类 [英] Structs vs classes in C++

查看:114
本文介绍了Structs与C ++中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中什么时候应该使用structs而不是类,反之亦然?我发现自己使用结构体,当一个成熟的类管理一些信息似乎过分,但想表明包含的信息都是相关的。我想知道什么是一些很好的指导方针,以便能够告诉何时比另一个更合适?



编辑:
在阅读材料时找到这些链接在提交问题后,显示的堆栈溢出相关:





从技术上讲,两者之间的唯一区别是结构是public的:默认情况下和类是private:

p>除此之外,没有技术上的差异。



struct vs class则成为语言的纯粹表达的细微差别。



通常,避免将复杂的方法放在结构中,大多数时候structs数据成员将保持公开。


$ b

struct = data是非常简单的辅助方法



class =强封装,仅通过方法


修改/访问数据

When should someone use structs instead of classes or vice versa in C++? I find myself using structs when a full-blown class managing some information seems like overkill but want to indicate the information being contained are all related. I was wondering what are some good guidelines to be able to tell when one is more appropriate than the other?

Edit: Found these links while reading the material Stack Overflow indicated was related after the question was submitted:

When should you use a class vs a struct in C++?
What are the differences between struct and class in C++

解决方案

Technically, the only difference between the two is that structs are public: by default and classes are private:

Other than that, there is no technical difference.

struct vs class then becomes a purely expressive nuance of the language.

Usually, you avoid putting complicated methods in a struct, and most of the time structs data members will stay public. In a class you want to enforce strong encapsulation.

struct = data is public, with very simple helper methods

class = strongly encapsulated, data is modified / accessed only through methods

这篇关于Structs与C ++中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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