High-quality C ++/C Programming Guide (2)-constants in the class

Source: Internet
Author: User

Sometimes we want some constants to be valid only in the class. Since the macro constants defined by # define are global and cannot be achieved, it is assumed that we should use const to modify data members. The const data member does exist, but its meaning is not what we expected. The const data member is a constant only within the lifetime of an object, but it is variable for the entire class, because the class can create multiple objects, the values of the const data members of different objects can be different.

The const data member cannot be initialized in the class declaration.The following usage is incorrect because the compiler does not know what the size value is when the class object is not created.

Class

{...

Const int size = 100; // error, attempted to initialize the const data member in the class declaration

Intarray [size]; // error, unknown size

};

The const data member initialization can only be performed in the initialization table of the class constructor, for example

Class

{...

A (INT size); // Constructor

Const int size;

};

A: A (INT size): size (size) // initialization table of the constructor

{

...

}

A A (100); // the size of object A is 100

A B (200); // the size of object B is 200

How can we create constants that are constant throughout the class? Don't count on the const data member. We should use the enumerated constants in the class. For example

Class

{...

Enum {size1 = 100, size2 = 200}; // enumerated constant

Int array1 [size1];

Int array2 [size2];

};

Enumerated constants do not occupy the storage space of objects. They are fully evaluated during compilation. The disadvantage of an enumerated constant is that its implicit data type is an integer, its maximum value is limited, and it cannot represent a floating point number (such as Pi = 3.14159 ).

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.