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这样的好处就是当构造函数需要多个初始化时就会变得很简洁。

原文地址:https://www.cnblogs.com/h-hg/p/8784319.html