加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

是否有一种方法可以确保类成员函数不会更改任何类数据成员?

发布时间:2020-12-16 06:48:19 所属栏目:百科 来源:网络整理
导读:让我们说我有一个 class Dictionary{vectorstring words; void addWord(string word)//adds to words{/...}bool contains(string word)//only reads from words{//...}} 有没有办法使编译器检查包含不更改单词向量. Ofc这只是一个类数据成员的例子,我希望它
让我们说我有一个

class Dictionary
{
vector<string> words;  
void addWord(string word)//adds to words
{
/...
}
bool contains(string word)//only reads from words
{
//...
}
}

有没有办法使编译器检查包含不更改单词向量. Ofc这只是一个类数据成员的例子,我希望它能与任意数量的数据成员一起使用.
附:我知道我没有公开:私有:我故意把它留下来让代码更短,问题更清晰.

解决方法

如果希望编译器强制执行此操作,则声明成员函数const:

bool contains(string word) const
{
    ...
}

const函数不允许修改其成员变量,并且只能调用其他const成员函数(自己的或其成员变量的函数).

此规则的例外是成员变量声明为可变. [但可变不应该用作通用的const解决方法;它仅仅适用于对象的“可观察”状态应该是const的情况,但内部实现(例如引用计数或延迟评估)仍然需要更改.

还要注意const不会通过例如传播.指针.

总结如下:

class Thingy
{
public:
    void apple() const;
    void banana();
};

class Blah
{
private:
    Thingy t;
    int *p;
    mutable int a;

public:
    Blah() { p = new int; *p = 5; }
    ~Blah() { delete p; }

    void bar() const {}
    void baz() {}

    void foo() const
    {
        p = new int;  // INVALID: p is const in this context
        *p = 10;      // VALID: *p isn't const

        baz();        // INVALID: baz() is not declared const
        bar();        // VALID: bar() is declared const

        t.banana();   // INVALID: Thingy::banana() is not declared const
        t.apple();    // VALID: Thingy::apple() is declared const

        a = 42;       // VALID: a is declared mutable
    }
};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读