Can I create anonymous classes in C++ and capture the outside variables like in Java?

后端 未结 5 599
挽巷
挽巷 2020-12-23 13:52

In Java, when I need a callback function, I have to implement an anonymous class. Inside the anonymous class, I can access the outside variables if they\'re final

5条回答
  •  眼角桃花
    2020-12-23 14:37

    It is not the anonymity of the class that restricts access to the outside variables. In the question, y is not accessible because the class was defined locally within a function.

    There are a couple of restrictions for classes defined locally. First, they can only access local variables that are static, but can access any other variable that is available to the scope of the function. Also, local classes can not have static data members.

    As for anonymous classes, you can not have constructors nor destructors. All member functions must be declared inside the class definition. It can not have static static members, this includes const static integral members that normally can be instantiated inside of a class definition. Also inheritance is not allowed.

    Anonymous classes are an obscure corner of C++ and have little practical value. Lambda functions and other techniques are a lot more flexible. But who knows, perhaps in some situations it could help with code readability.

提交回复
热议问题