Why is there a class keyword in C++?

后端 未结 5 1795
無奈伤痛
無奈伤痛 2020-12-11 15:50

This question came to my mind when I learned C++ with a background of C. Even if there was a struct why did Stroustrup felt it was necessary to introduce the <

5条回答
  •  离开以前
    2020-12-11 15:53

    The literal answer has already been given: "struct members are public by default, classes members are private by default". And most programmers explicitly identify all their sections as private, protected or public anyway.

    So literally speaking there's nothing you can do with a class you can't do with a typedef struct.

    However, a lot of C++ users use the "struct" to also identify C++ entities that are "plain old data structures". The idea of PODS is a very useful C++ concept - PODS are easily constructed, copied, and "have no surprises", while classes are much more dangerous.

    For example, PODS can be initialized into arrays at compilation time, which makes them very useful indeed for static tables.

    So I strongly recommend you follow the same convention - structs are PODS, anything else is a class.

提交回复
热议问题