Why does C need “struct” keyword and not C++?

后端 未结 6 785
臣服心动
臣服心动 2020-11-27 03:38

I\'ve always been a little confused about what\'s going on here:

#include 

int main() {  
    timeval tv;
    tv.tv_sec = 1;

    for (;;) {
         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 04:25

    Consider the original idea of C++ (or, when it was just an idea, "C with classes"), that of an OO-oriented language that was compatible with C to the point where most valid C programs were also valid C++ programs.

    C++ built its class model by starting with C's struct and adding some further functionality:

    1. Inheritance (though you can come close in C with having the first member of a struct the struct you want to "inherit" from).
    2. Information hiding (through public, private etc)
    3. Member methods (which were originally turned by macros into C code outside the struct with an added this parameter - many implementations are still similar in practice).

    At this point there were two problems. The first is that the default access had to be public, since C has no information hiding and therefore from a C++ perspective has everything public. For good OO one should default to private. This was solved by adding class which is pretty much identical to struct except for the default is private rather than public.

    The other is that this OO perspective should have timeval or any other class/struct on the same "footing" as int or char, rather than constantly annotated in the code as special. This was solved by relaxing the rule that one must place struct (or class) before the name of the type in declaring a variable of that type. Hence struct timeval tv can become timeval tv.

    This then influenced later C-syntax OO languages, like Java and C# to the point where, for example, only the shorter form (timeval tv) would be valid syntax in C#.

提交回复
热议问题