[转载]struct vs class in C++

援引自:https://blogs.mentor.com/colinwalls/blog/2014/06/02/struct-vs-class-in-c/

文中提到的3个例子

I will start by defining a struct in C. I would see it as a customized, composite data type, which may be constructed from the existing built-in data types [int, char, etc.], bit fields [integers of specified bit size] and other structs. This example shows a simple example of a struct definition, along with the declaration of a variable of that type and access to one of the fields. A struct is a handy and flexible way to represent data. Similar facilities exist in most modern programming languages.

**How does a C++ class differ from a C struct? **There are a few differences. The key ones are:

  • A class can also contain functions [called methods].
  • The member variables and methods are hidden from the outside world, unless their declaration follows a public label.
  • There can be a pair of special methods – the constructor and destructor – that are run automatically when an instance of the class [an object] is created and destroyed.
  • Operators to work on the new data type can be defined using special methods [member functions].
  • One class can be used as the basis for the definition of another [inheritance].
  • Declaring a variable of the new type [an instance of the class; an object] requires just the name of the class – the keyword class is not required.

Most of these are illustrated in the example here.

But what about a struct in C++? The last example here gives a clue. The only difference between a struct and class in C++ is the default accessibility of member variables and methods. In a struct they are public; in a class they are private.

Having imparted this information, I urge you not to exploit it too heavily. A key priority when you are writing code is to ensure that it is readable [=maintainable]. Somebody – it could be you – might need to look at this code in a year’s time and understand what it does. I have heard advice as follows: Assume that the person that will maintain your code is an armed psychopath, who has limited patience and knows your home address.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,493评论 0 23
  • 我能想到的最动听的声音:是爱人,孩子们均匀的呼吸声。 什么时候开始有了这样的感受呢?是大儿子鼻塞一次后。看他呼吸不...
    漫漫无忧阅读 2,206评论 16 10
  • 我认识一个掌心有痣的人。 以前只是觉得好奇,因为传统命理讲,掌中有痣的人是天煞孤星命,就是一世孤独。现在以相学角度...
    晶晶亮的沙子阅读 4,941评论 2 3
  • 田刘,我发小,同年而生,一起长大。 一直觉得我和他之间彼此是心灵最近,都尝遍孤独的痛苦,才拥有灵魂的相栖。 在他那...
    六六sy阅读 2,920评论 0 2

友情链接更多精彩内容