C + + Union refinement

Source: Internet
Author: User

Union is an unnoticed keyword, and it does not appear in C + + for the sake of inheriting the C language. Its role is mainly to save memory space, in embedded programming is useful. But in C + +, which is designed for contemporary microcomputers, it is not useless. Take a look at the following code:

class a{private:    int a[];  Public :    A (int N): a[0] (n) {}}; // Wrong Code

Do you think this code can be compiled? Yes, that should be the case. But to run the compiler, you will get the following error expected ' (' before ' [' token:a (int n): a[0] (n) {}. The amount ... It seems that array elements cannot be used for list initialization. At this point, we can use union to solve the problem skillfully.

class a{private:    Union {        int a[];         int a0;    };  Public :    A (int  N): A0 (n) {}};

The principle is not difficult to understand, according to the Union mechanism, A0 and a[0] is actually a common int, that is, A0 and a[0] the same address, the initialization of A0 is also the initialization of a[0].

C + + Union refinement

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.