类作用域
(1)作用域为类的常量
使符号常量的作用域为类很有用
class Bakery
{
private:
const int Months = 12;//不合法
};
上面这样做行不通,因为声明类只是描述了对象的形式,并没有创建对象。因此在创建对象前,将设有用于存储值的空间不行;
然而有两种方式可以实现将符号常量的作用设为类作用域
a、在类中声明一个枚举
class Bakery
{
private:
enum{Month = 12};//在类中声明枚举作用域为整个类
double costs[Month];
};//注意:用这种方式声明枚举并不会创建类数据成员。也就是说所有对象中都不包含枚举,另外,Month只是一个符号名称,在作用域为整个类的代码中,编译器将用12替换它;
b、C++提供了另一种在类中定义常量的方式——使用关键字static
class Bakery
{
private:
static const int Month = 12;
double costs[Month];
};
这将创建一个名为Month的常量,该常量将与其他静态变量存储在一起,而不是存储在类对象中,因此,只有一个Month常量被所有Bakery对象共享
include
include
using namespace std;
class Bakery
{
private:
static const int Month = 12;//静态类成员
int x;
};
void main()
{
Bakery tmp;
cout << sizeof(tmp) << endl;//输出4
system(“pause”);
}
(2)作用域内枚举
传统枚举存在一些问题,其中之一是两个枚举定义中的枚举量可能发生冲突。
enum egg{Small, Medium, Large};
enum t_shirt{Small, Medium, Large, Xlarge};
这将无法通过编译,因为两个枚举位于同一个作用域内,他们将发生冲突。为避免这样,C++11提供了一种新枚举,其枚举的作用域为类。
enum class egg {Small, Medium, Large, Jumbo};
enum class t_shirt {Small, Medium, Large, Jumbo};
也可以使用struct代替class,无论使用 哪种方式,都需要使用枚举名来限定枚举量:
egg choice = egg::Large;
t_shirt Floyd = t_shirt::Large;
枚举量的作用域为类后,不同枚举定义中的枚举量就不会发生名称冲突了;