旧代码中的"enum hack"

本节课主要说明:

 

我们可以把

static const int size = 1000;替换为

enum { size = 1000};

   

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

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 对象和成员函数

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 成员函数
  

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

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

posted @ 2013-04-03 22:31  wiessharling  阅读(351)  评论(0编辑  收藏  举报