Class constant array Initialization

Source: Internet
Author: User

(1 ). move a [10] to the class level and change const int A [10] to static const int A [10]. You can think about it seriously. Since a [10] is a const, so do each object really need a separate a [10? Most of the time, the answer should be no. The class is defined as follows:

Class

{

Public:

A (){}

PRIVATE:

Static const int A [10];

};

Const int A: A [2] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; // In the implementation file.

(2) Change the array to a pointer, that is, change const int A [10] to const int * const A. The class is defined as follows:

Const int Ca [10] = {, 5, 0}; // note

Class

{

Public:

A (): A (CA ){}

PRIVATE:

Const int * const;

};

 

(3) If you want to keep a copy of the constant array in each object, you can also use vector instead.
# Include <vector>
Using namespace STD;
//...
Const int Ca [5] = {1, 2, 3, 4, 5 };
Class
{
Public:
A (): A (Ca, Ca + 5 ){}
PRIVATE:
Const vector;
};

 

 

In view of these three methods, my friends who visit my blog also hope to discuss their respective advantages and disadvantages. Even if they leave a footprint, my blog keeps silence when so many people visit it every day, after reading so many posts, you have to go back to them.

 

I think the constant array members are the features of the class. Instead of the features of objects. So it should be declared as static. For this reason, I recommend the first method.

 

You have also made comments and discussed them.

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.