乐闻世界logo
搜索文章和话题

What is the difference between struct and class?

1个答案

1

Default Access Specifiers:

  • struct: The default access specifier is public, meaning that members are accessible from outside the struct by default.
  • class: The default access specifier is private, meaning that members are not accessible from outside the class by default unless explicitly declared public.

Default Inheritance:

  • When deriving a struct or class from another struct or class, struct uses public inheritance by default, whereas class uses private inheritance by default.

Example: Consider the following two definitions: one is a struct, and the other is a class:

cpp
struct MyStruct { int x; }; class MyClass { int x; };

In these examples, the member x of MyStruct is public by default, meaning it can be accessed directly from outside the struct:

cpp
MyStruct obj; obj.x = 10; // Allowed

For MyClass, the member x is private by default, meaning it cannot be accessed directly from outside the class:

cpp
MyClass obj; obj.x = 10; // Compilation error because x is private

Summary: Although struct and class can be used interchangeably in technical terms (especially in C++), by convention, struct is typically used for smaller data structures primarily for data storage rather than behavior. class is usually used for defining more complex objects that include both data and behavior (functions). This convention enhances code readability and maintainability.

2024年8月9日 17:50 回复

你的答案