Static member Initialization

Source: Internet
Author: User

1. For non-static data members, each class object has its own copy, while the static data member has only one copy for each class type. Because static data members are allocated in the global data zone, they must exist when the program starts running, therefore, the space allocation and initialization of static data members cannot be completed in the main function or other functions (so static data members are not allowed in local classes ). In this way, the space allocation and initialization of static data members are only possible in the following three ways: (a) Class header file: class declaration. However, there is an unavoidable problem: for static data members, there can only be one definition in the program, and the class header file may be repeatedly referenced and the definition is repeated; (B) the global data declaration and definition before the main function: This method also has a problem. Every program that uses this class must define the static members of this class here, which is unrealistic. (c) internal Implementation of class definition: This is the most ideal method. You only need to include the header file When referencing.

2. Simple variable Initialization

#include <string>
class Account {
// ...

private:
static const string name;
};
const string Account::name( "Savings Account" );

3. initialize a one-dimensional array

class mydlg
{
  static mychilddlg *dlgs[3];
}

static mychilddlg* mydlg::dlgs[3]={ 0 , 0 , 0 };

4. Two-dimensional array Initialization

Method 1:
Define a static function in the class to initialize this array. Call this function in the initialization code of the Program for initialization.

Method 2:
Write a class to wrap this array. The class can have constructor and be initialized in the constructor.

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.