c++实例研究

从0开始

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  104 随笔 :: 0 文章 :: 20 评论 :: 0 Trackbacks
#include <iostream>
#include 
<cstdlib>
using namespace std;

class Foo
{
public:
    Foo(
int n):val(n),changed(false){}
    
int getVal()const
    
{
        Foo 
*fp = const_cast<Foo*>(this);
        fp
->changed=true;
        
//changed=true; //error: in read-only structure
        return val;
    }
;
    
bool isVisit()const{return changed;}
private:
    
int val;
    
bool changed;
}
;

int main()
{
    Foo f(
10);
    cout
<<f.isVisit()<<endl;
    cout
<<f.getVal()<<endl;
    cout
<<f.isVisit()<<endl;
    system(
"PAUSE");
    
return 0;
}


一种更好的方法是使用mutable关键字,表示即使在const情况下,仍然能被修改
#include <iostream>
#include 
<cstdlib>
using namespace std;

class Foo
{
public:
    Foo(
int n):val(n),changed(false){}
    
int getVal()const
    
{
        changed
=true//OK
        return val;
    }
;
    
bool isVisit()const{return changed;}
private:
    
int val;
    mutable 
bool changed;
}
;

int main()
{
    Foo f(
10);
    cout
<<f.isVisit()<<endl;
    cout
<<f.getVal()<<endl;
    cout
<<f.isVisit()<<endl;
    system(
"PAUSE");
    
return 0;
}

如果一个类中有很多需要被修改,可以单独作为一个成员类
#include <iostream>
#include 
<cstdlib>
using namespace std;

class Bar
{
public:
    Bar():changed(
false),val_count(0){}
    
bool changed;
    
int val_count;
}
;

class Foo
{
public:
    Foo(
int n):val(n),b(new Bar()){}
    
int getVal()const
    
{
        b
->changed=true//ok
        b->val_count++;
        
return val;
    }
;
    
bool isVisit()const{return b->changed;}
    
int getValCount()const{return b->val_count;}
private:
    
int val;
    Bar
* b;
}
;

int main()
{
    Foo f(
10);
    cout
<<f.isVisit()<<endl;
    cout
<<f.getValCount()<<endl;
    
    cout
<<f.getVal()<<endl;
    cout
<<f.isVisit()<<endl;
    cout
<<f.getValCount()<<endl;

    cout
<<f.getVal()<<endl;
    cout
<<f.isVisit()<<endl;
    cout
<<f.getValCount()<<endl;

    system(
"PAUSE");
    
return 0;
}


特别注意上例中,指针b的初始化的写法,其实,在构造函数冒号后的member(val)相当于member=val
posted on 2010-05-01 11:10 elprup 阅读(371) 评论(0)  编辑 收藏 引用 所属分类: c++实例

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理