Static member variable initialization, vector type variable Initialization

Source: Internet
Author: User

in some cases, when writing C ++ classes, you want to use static initialize functions to initialization is performed on the f66; "> static member. For example, STD: MAP member or STD :: Add fixed content to the vector member. This can be easily implemented through static blocks in Java. But what should I do in C ++?

If you wantInitializationA commonStaticYou only need to define the member in the implementation file (source file) and assign the initial value to it. For example:

Class Test1 {
Public :
Static   String Emptystring;
};

string test1 :: emptystring = " " ;
// also can be
// string test1: emptystring;
/// string test1: emptystring (" ");

StaticFunctions cannot be called directly like this. However, use C ++InitializationCommon member features to callStaticInitializationFunction. Of course, this requires defining an additionalStaticMember variables to help. For example:

Class Test2 {
Public :
Static   Vector < String > Stringlist;
Private :
Static   Bool _ Init;
Static   Bool Init (){
Stringlist. push_back ( " String1 " );
Stringlist. push_back ( " String2 " );
Stringlist. push_back ( " String3 " );

Return True;
}
};

Vector<String>Test2: stringlist;
BoolTest2 ::__ init=Test2: Init ();

In the above exampleStaticMember _ init is called by the way.StaticInitializationThe init () function achieves the intended purpose.

 

Project Example:

# Include "stdafx. H"
# Include "ctrackview. H"
# Include "databaseinfo. H"

Cvss_rect ctrackview: m_worldrt (0, 0, 0 );
Crect ctrackview: m_screenrt (0, 0, 0, 0 );
HDC ctrackview: m_hdc = NULL;
V_vnopoint ctrackview: v_vnopt;
Ctrackview: ctrackview (void)
{
}

Ctrackview ::~ Ctrackview (void)
{
}

.......

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.