Quick initialization of member variables in C++11

Posted by daloss on Sun, 05 Jan 2020 10:22:55 +0100

color=#00ffff
1. The so-called "in place declaration" method is supported in C + + 98. The so-called in place declaration is to use the equal sign "=" in the class declaration to initialize the static member constant. However, when the equal sign "=" is directly used to declare variables in a class, the requirements are more stringent. It must meet two conditions, otherwise, compilation fails.

(1) This static member variable in the class needs to meet the "constant nature". If it does not meet the static variable constant nature, it cannot be declared in place.
(2) On the basis of (1), it also needs to satisfy that the static constant member must be: integer type or enumeration type.

The above two conditions must be met at the same time before local initialization can be carried out. Otherwise, C++98 does not support them. As shown in code 1:
Compiled on linux, the version number of g + + is: g + + (Ubuntu 4.8.4-2ubuntu 1 ~ 14.04.4) 4.8.4
At compile time, all the variables except d and g can be compiled. This is actually an extension of GNU to C + +, which does not follow the standard of C + +.

/*************************************************************************
 * File Name: C++98.cpp
 * Author:    The answer
 * Function:  Other        
 * Mail:      2412799512@qq.com 
 * Created Time: 2018 September 9, 2009 Sunday 14:37:29
 ************************************************************************/

#include<iostream>
using namespace std;

enum{RED,ORAGE,YELLOW,GREEN,BLUE,WHITE};

class Test{
public:
    Test():a(0){}
    Test(const int v):a(v){}
    ~Test(){}

protected:
    int a;
    const static int b = 1;
    const static int c = RED;

     //C++98.cpp:24:20: error: ISO C++ forbids in-class initialization of non-const static member 'Test::d'
    static int d = 2;  //Common member variable d, unable to compile
    static const float e = 1.0;  
    static const double f = 2.0; 

    //C++98.cpp:29:28: error: invalid in-class initialization of static data member of non-integral type 'const char*'
    static const char* g = "l";  //Failed to compile

};

int main(int argc,char **argv)
{

    return 0;
}

When using Visual Studio, in addition to the static constant b and static constant c can be compiled, other errors will be reported.

public:
    Test():a(0){}
    Test(const int v):a(v){}
    ~Test(){}

protected:
    int a;                       //Normal member variable a, unable to compile
    const static int b = 1;
    const static int c = RED;

    static int d = 2;            //Static member variable d, unable to compile
    static const float e = 1.0;  //Static constant member e, unable to compile
    static const double f = 2.0; //Static constant member f, cannot be compiled
    static const char* g = "l";  //Static constant pointer g, unable to compile
};

Topics: Linux Ubuntu