C++ accessor 和 mutator 方法有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9627093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:05:30  来源:igfitidea点击:

What is the difference between accessor and mutator methods?

c++

提问by Nawshad Farruque

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

访问器和修改器有什么不同?一个例子和解释会很棒。

回答by LeopardSkinPillBoxHat

An accessoris a class method used to readdata members, while a mutatoris a class method used to changedata members.

一个存取器是用于一个类方法数据成员,而突变是用于一个类方法的变化的数据成员。

Here's an example:

下面是一个例子:

class MyBar;

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

    private:
        MyBar mMyBar;
}

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:

最好的做法是创建数据成员private(如上例所示)并仅通过访问器和修改器访问它们。这是出于以下原因:

  • You know when they are accessed (and can debug this via a breakpoint).
  • The mutator can validate the input to ensure it fits within certain constraints.
  • If you need to change the internal implementation, you can do so without breaking a lot of external code -- instead you just modify the way the accessors/mutators reference the internal data.
  • 您知道何时访问它们(并且可以通过断点对其进行调试)。
  • mutator 可以验证输入以确保它符合某些约束。
  • 如果您需要更改内部实现,您可以在不破坏大量外部代码的情况下这样做——相反,您只需修改访问器/修改器引用内部数据的方式。

回答by Duck

class foo
{
    private:

        int a;
    public:
        int  accessA() const { return(a);}
        void mutateA(const int A) { a = A;}
}

Also known as getters and setters and probably a dozen other terms.

也称为 getter 和 setter,可能还有十几个其他术语。