accessor和mutator方法有什么区别? [英] What is the difference between accessor and mutator methods?

查看:4634
本文介绍了accessor和mutator方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

访问器和mutator如何不同?

How are accessors and mutators different? An example and explanation would be great.

推荐答案

访问器是一种类方法,用于读取数据成员,而 mutator 是用于更改数据成员的类方法。

An accessor is a class method used to read data members, while a mutator is a class method used to change data members.

下面是一个例子:

class MyBar;

class Foo
{
    public:
        MyBar GetMyBar() const { return mMyBar; } // accessor
        void SetMyBar(MyBar aMyBar) { mMyBar = aMyBar; } // mutator

    private:
        MyBar mMyBar;
}

最好的做法是使数据成员 code>(如上例所示),并且只能通过访问器和mutator访问它们。这是因为以下原因:

It's best practice to make data members private (as in the example above) and only access them via accessors and mutators. This is for the following reasons:


  • 您知道他们何时被访问(并且可以通过断点调试)。

  • mutator可以验证输入以确保其适合某些限制。

  • 如果需要更改内部实现,您可以这样做,

这篇关于accessor和mutator方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆