C++ 常函数修改数据成员一题

1、问题描述

有类如下

class A_class
{
    void f() const
    {
        ...
    }
};

在上面这种情况下,如果要修改类的成员变量,该怎么办?

 

2、析

C++中,类的数据成员加上mutable后,修饰为const的成员函数,就可以修改它了 。

 

3、举例如下

测试类头文件,Asa.h

#ifndef ASA_H
#define ASA_H

class Asa
{
public:
    Asa();
    int incr() const;

private:
    mutable int mobi;
};

#endif // ASA_H

 

测试类实现体,Asa.cpp

#include "asa.h"

Asa::Asa()
{
    this->mobi = 0;
}

int Asa::incr() const
{
    return ++mobi;
}

 

主类的调用main.cpp

#include <iostream>
#include "asa.h"

using namespace std;

int main()
{
    Asa *p = new Asa();
    cout << p->incr() << endl;

    return 0;
}

 

posted @ 2014-12-25 09:16  阿青1987  阅读(453)  评论(0编辑  收藏  举报