[转载]struct vs class in C++

2016-10-08  本文已影响43人  PatrickHC
援引自: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:

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.

上一篇 下一篇

猜你喜欢

热点阅读