zoukankan      html  css  js  c++  java
  • c++类中的常量

    定义属于这个类范围的常量

    class test
    {
    private:
        enum {Months = 12};
    };
    

      这种声明枚举不会创建类数据成员,这里枚举只是为了创建类数据成员,因此不用提供枚举名。类似上面的例子还有ios_base::fixed等。

    扩充:c++11作用域内的枚举

    enum egg {Small, Medium, Large, Jumbo};
    enum t_shirt {Small, Medium, Large, Xlarge};
    

      编译器提示重复定义SmallMediumLargeJumbo。因为egg Small和t_shirt Small位于相同的作用域内。
      c++11提供了一种新的枚举,它的作用域为类。可以使用关键字class或者struct

    enum class egg {Small, Medium, Large, Jumbo};
    enum class t_shirt {Small, Medium, Large, Xlarge};
    egg choice = egg::Large;
    t_shirt Floyd = t_shirt::Large;
    

    const常量

    class test
    {
    private:
        const int n;
    public:
        test():n(100){}
    }
    

      类的声明只是声明了类的形式,并没有创建对象,因此,在创建对象前,将没有用于储存值的空间。

    c++98与c++11的区别
      在C++98标准里,只有static const声明的整型成员能在类内部初始化,并且初始化值必须是常量表达式。这些限制确保了初始化操作可以在编译时期进行。

    class X {
        static const int m1 = 7;   // 正确
        const int m2 = 7;    // 错误:无static
        static int m3 = 7;              // 错误:无const
        static const string m5 = “odd”; //错误:非整型
    };
    

      C++11的基本思想是,允许非静态(non-static)数据成员在其声明处(在其所属类内部)进行初始化。这样,在运行时,需要初始值时构造函数可以使用这个初始值。现在,我们可以这么写:

    class A {
    public:
        int a = 7;
    };
    //它等同于使用初始化列表:
    class A {
    public:
        int a;
        A() : a(7) {}
    };
    

      c++11这样的好处就是当构造函数需要多个初始化时就会变得很简洁。

  • 相关阅读:
    org.hibernate.annotationexception no identifier specified for entity
    PL/SQL Developer 中文乱码解决
    cron表达式
    mysql远程连接的设置
    linux查看端口对应的程序及pid
    安卓开发分享功能,分享到facebook网页上不显示图片的问题
    win7下解压安装mysql的方法
    总结一下论文写作过程中的一些东西
    java中可以让程序暂停几秒执行的代码
    Neo4j图数据库使用
  • 原文地址:https://www.cnblogs.com/h-hg/p/8784319.html
Copyright © 2011-2022 走看看