zoukankan      html  css  js  c++  java
  • STL容器[30]

    index.cpp:59: in-class initialization of static data member of non-integral type `const string'
    index.cpp:60: in-class initialization of static data member of non-integral type `const string'
    index.cpp:61: in-class initialization of static data member of non-integral type `const string'

    Static Class Members may not be Initialized in a Constructor

    A common mistake is to initialize static class members inside the constructor body or a member-initialization list like this:

    
    class File
    {
    private:
    static bool locked;
    private:
    File();
    //…
    };
    File::File(): locked(false) {} //error, static initialization in a member initialization list
    

    Although compilers flag these ill-formed initializations as errors, programmers often wonder why this is an error. Bear in mind that a constructor is called as many times as the number of objects created, whereas a static data member may be initialized only once because it is shared by all the class objects. Therefore, you should initialize static members outside the class, as in this example:

    
    class File
    {
    private:
    static bool locked;
    private:
    File() { /*..*/}
    //…
    };
    File::locked = false; //correct initialization of a non-const static member
    

    Alternatively, for const static members of an integral type, the Standard now allows in-class initialization:

    
    class Screen
    {
    private:
    const static int pixels = 768*1024; //in-class initialization of const static integral types
    public:
    Screen() {/*..*/}
    //…
    };
    
  • 相关阅读:
    最近相对闲点,写个笔记2
    最近相对闲点,写个笔记
    ORACLE 调优
    静态工厂方法与构造函数 创建类 区别
    组合与继承 区别
    Java异常
    abstract class 和 interface 区别
    java中的io系统详解
    Tomcat Apache 区别
    Vmware 下的网络模式配置
  • 原文地址:https://www.cnblogs.com/motadou/p/1631522.html
Copyright © 2011-2022 走看看