我是靠谱客的博主 标致小蘑菇,这篇文章主要介绍旧代码中的"enum hack",现在分享给大家,希望可以做个参考。

本节课主要说明:

 

我们可以把

static const int size = 1000;替换为

enum { size = 1000};

   

在旧版的c++ 中,不支持在类中使用static const。这意味着const对在类中的常量表达式不起作用,不过,人们还是想得做到这一点。使用不带实例的无标记的enum(通常称为 enum hack)。例如下面代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
class Bunch { enum { size = 1000}; int i[size]; }; int _tmain(int argc, _TCHAR* argv[]) { cout<<"sizeof(Bunch) = "<<sizeof(Bunch)<<", sizeof(i[1000] = "<<sizeof(int[1000])<<endl; return 0; }

输出:4000   4000   这说明了enum { size = 1000};并不占用内存
所以,上面的例子说明了:

我们可以把

static const int size = 1000;替换为

enum { size = 1000};

2、const 对象和成员函数

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class X { int i; public: X(int ii); int f() const; int g(); int ff() const; }; X::X(int ii):i(ii) { } int X::ff() const { return i; } int X::g() { i++; return i; } int X::f() const { ff(); //g(); error 在f函数内都不能改变数据成员,函数g改变了数据成员i return i; }

3、const 对象与const 成员函数或非const 成员函数
  

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Quoter { int lastquote; public: Quoter(); int lastQuote() const; const char* quote(); }; Quoter::Quoter() { lastquote = -1; } int Quoter::lastQuote() const { return lastquote; } const char* Quoter::quote() { //change the data member lastquote; //like lastquote++; static const char* quotes[] = {"1", "", "2", "3", "4", "6"}; return quotes[lastquote]; } int _tmain(int argc, _TCHAR* argv[]) { Quoter q; const Quoter cp; cp.quote();//error non const function cp.lastQuote();//ok q.lastQuote(); //ok q.quote(); //ok int a; cin>>a; return 0; }

构造函数和析构函数都不是const成员函数,因为他们在初始化和清除时,总是对对象作修改。

要在const 函数中改变数据成员的方法:

1、强制转换常量性:

  取this指针,并把强制转换成指向当前类型对象的指针。看来this已经是所需要的指针,但是,在const 成员函数内部,它实际上是一个const指针,所以,还应把它强制转换成一个普通指针。(ElementType*)this

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Y { int i; public: Y(); void f() const; }; Y::Y() { i = 0; } void Y::f() const { i++; //error ((Y*)this)->i++;//OK (const_cast<Y*>(this)->i++; } int main() { const Y yy; yy.f(); //Actually changes it }


2、关键字mutable

  在要修改的数据成员前加关键字mutable;

  //详细请看关键字mutable

转载于:https://www.cnblogs.com/wiessharling/archive/2013/04/03/2998811.html

最后

以上就是标致小蘑菇最近收集整理的关于旧代码中的"enum hack"的全部内容,更多相关旧代码中的"enum内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(71)

评论列表共有 0 条评论

立即
投稿
返回
顶部