《C++ Primer》为何使用struct关键字定义类类型?
struct Instead of class for the Sales_data "Class" in C++ Primer? Great question—this is a super common point of confusion when learning C++ class basics, especially if you’re coming from a C background. Let’s break down exactly why the authors made this choice:
Default Access Permissions Match the Design Goal
The only technical difference betweenstructandclassin C++ is their default member access level (and default inheritance behavior, which doesn’t matter here):- A
structmakes all members public by default. - A
classmakes all members private by default.
The Sales_data type is explicitly designed to let users directly access its data elements (as the book states: "let users directly access data elements and implement the required operations themselves"). Using
structmeans we don’t need to add a clunkypublic:block to exposebookNo,units_sold, andrevenue—it’s clean and aligns perfectly with the intended use. If we usedclass, the code would require extra boilerplate:class Sales_data { public: // Mandatory to make members accessible std::string bookNo; unsigned units_sold = 0; double revenue = 0.0; };- A
Semantic Conventions Signal Intent
Even thoughstructandclassare technically equivalent (both define C++ class types), developers use them to communicate intent:structis typically reserved for simple, data-first types where members are meant to be public, with little to no encapsulation or member functions.classis used for types with encapsulation, member functions, and a clear separation between public interface and private implementation.
The authors are following this community convention here—Sales_data is a straightforward aggregate data structure, so
structfeels more idiomatic thanclass.Smooth Transition for C Learners
C++ Primer aims to be accessible to readers coming from C. In C,structis the standard way to group related data. Usingstructhere helps bridge that gap, showing that C++ extends the familiar Cstructinto a full class type while keeping the syntax simple for basic use cases.Pedagogical Progression
The book teaches class concepts incrementally. Starting withstructlets readers grasp the idea of a user-defined data type first, without getting overwhelmed by access modifiers and encapsulation. Later, when introducing more complex classes with member functions and private data, the authors will switch toclassto emphasize those advanced patterns.
To sum it up: The choice of
structisn’t about technical limitations—it’s about aligning syntax with the type’s purpose, following community norms, and making the material easier to absorb for new learners.
内容的提问来源于stack exchange,提问作者Spellbinder2050

