Why is the semicolon not required but allowed at the end of a class definition?

前端 未结 5 1425
忘了有多久
忘了有多久 2020-12-18 18:57

I\'m trying to shift from C++ to Java.

What I wonder is, in C++, after a class definition, a semicolon (;) is required, but in Java it isn\'t.

T

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 19:33

    I'm not familiar with Java, but the reason why there's an extra semicolon needed is because you can define an anonymous class, inside functions. For instance:

    void routine(const int x, const int y)
    {
        class { public: int x; int y; } my_instance;
        my_instance.x = x;
        my_instance.y = y;
        // ... etc
    }
    

    You'll usually see this more with structs than with classes, to capture some important variables of a big class.

    void f(const BigClass& big_class)
    {
        struct { std::string str; int i; } props;
        props.str = big_class.GetFilename();
        props.i = big_class.GetID();
        // etc...
    }
    

提交回复
热议问题