I can not understand the declaration of structure in C ++

In C, we must use a structure prefix whenever we want to declare or define a structure. However, everything changed after the structure became a kind of class in C ++. We no longer need to use the struct prefix when declaring a structure. In this vein, I believe that the structure tag in C become the type name in C++ .

However, this does not mean that we cannot use the struct prefix. We can still use the prefix struct . For example, Bjarne Stroustrup, the creator of C ++, presents an example of declaring a structure with both the prefix struct and without it, which makes me puzzled.

The following are structure definitions that attempt to create a structure with an argument of template T. They compile fine, with no errors.

 template<class T> struct linked_list { T element; linked_list<T> *next; }; template<class T> struct linked_list { T element; struct linked_list<T> *next; }; 

Now below are declarations of functions whose return type and argument type are structures. Despite the fact that they do not differ from those described above, the first of them is below two function declarations, one with a structure prefix, gives me an error with Visual Studio C ++ 2012

 template<class T> struct linked_list<T> *add_list(T element, struct linked_list<T> *tail); template<class T> linked_list<T> *add_list(T element, linked_list<T> *tail); 

I really donโ€™t understand how everything works. I do not understand the differences between these declarations. Can someone give me a detailed explanation?

+7
c ++ c struct class structure
source share
2 answers

Other than C, in C ++, the struct (and class ) keyword can be omitted if there is no ambiguity. If there is ambiguity, you still have to use the struct keyword. A well-known example is POSIX ' stat : there is a struct stat and a stat function. Here you always need to use struct stat to indicate type.

+4
source share

You seem to understand well how you yourself explain. In C ++, the struct keyword is the same as the keyword class, but with a default value for public, not private members. Thus, by declaring a class using the struct keyword, you are not using it again referring to this class. It seems you are trying to use struct, as it will be used in C in the first example. For C ++, this is completely different.

-one
source share

All Articles