简体   繁体   中英

I can't understand the structure declaration in c++

In C, we have to use a struct prefix whenever we want to declare or define a structure. However, things have been changed once the structure became a kind of a class in c++. We no longer need to use a struct prefix when we declare a structure. In this vein, I guess the structure tag in C became a name of a type in C++ .

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

Below are structure definitions which try to make a structure with template argument T. These compile fine with no error.

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 function declarations whose return type and argument type are structures. Even though these are not that different from the above, the first one from below two function declarations, the one with a struct 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 things work. I don't understand the differences between these declarations. Could anyone give me a detailed explanation?

Other than in C, in C++ the struct (and class ) keyword may be omitted, if there is no ambuiguity. If there is ambiguity, you still have to use the struct keyword. A notorious example is POSIX' stat : there is a struct stat and a function stat . Here you always have to use struct stat to refer to the type.

You do seem to understand pretty well as you explain it yourself. In C++ the keyword struct is the same as the keyword class but with a default of public rather than private members. So having declared a class using the struct keyword you do not then use it again when referring to that class. You seem to be trying use struct as it would be used in C in the first example. This is just different for C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM