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

What is the difference between ' struct ' and 'typedef struct' in C++?

1个答案

1

In C++, the primary distinction between struct and typedef struct stems from their usage and historical context in C and C++.

1. Basic Usage of struct

In C++, struct is used to define a struct, which is a mechanism for combining multiple different data members into a single entity. Structs are commonly employed in C++ to represent data records. For example:

cpp
struct Person { std::string name; int age; }; Person p1 = {"John", 30};

Here, the Person struct contains two data members: name and age.

2. Usage of typedef struct

typedef is widely used in C to define a new name (alias) for an existing type. In C, you frequently encounter usage like:

c
typedef struct Person { char* name; int age; } Person;

Here, typedef struct not only defines a struct but also creates a new type name Person via typedef, enabling direct use of Person instead of struct Person to declare variables.

C++ Simplification

However, in C++, this typedef usage is unnecessary because C++ natively supports declaring variables using the struct type name without additional typedef. Consequently, in C++, it is standard to write:

cpp
struct Person { std::string name; int age; };

Then, you can directly declare variables such as Person p1; without typedef. This syntax is more concise and reduces code complexity.

Summary

Overall, in C++, struct alone suffices, and using typedef struct typically originates from C language conventions. For pure C++ projects, it is recommended to use simple struct definitions. This approach yields benefits including clearer, more concise, and intuitive code, which is particularly valuable when maintaining large C++ projects.

2024年7月25日 18:27 回复

你的答案