如何编写C ++ getter和setter [英] How to write C++ getters and setters

查看:189
本文介绍了如何编写C ++ getter和setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我需要为属性写一个setter和/或getter,我可以这样写:

If I need to write a setter and/or getter for a property I write it like this:

struct X { /*...*/};

class Foo
{
private:
    X x_;

public:
    void set_x(X value)
    {
        x_ = value;
    }
    X get_x()
    {
        return x_;
    }
};

但是我听说这是 Java风格的二传手,吸气剂,我应该用C ++风格编写。而且我被告知这是不充分的,甚至是不正确的。这意味着什么?

However I have heard that this is the Java style of writing setters and getters and that I should write it in C++ style. Moreover I was told it is ineficient and even incorrect. What does that mean? How can I write the setters and getters in C++?

我该如何用C ++编写setter和getters?假设对getter和/或setter的需求是有道理。例如。

推荐答案

属性有两种不同形式出现在标准库中,我将其归类为面向身份和面向价值。选择哪种选项取决于系统应如何与 Foo 进行交互。都不是更正确的。

There are two distinct forms of "properties" that turn up in the standard library, which I will categorise as "Identity oriented" and "Value oriented". Which you choose depends on how the system should interact with Foo. Neither is "more correct".

面向身份

class Foo
{
     X x_;
public:
          X & x()       { return x_; }
    const X & x() const { return x_; }
}

在这里,我们将 reference 返回给基础对象 X 成员,它使呼叫站点的双方都能观察到对方发起的更改。 X 成员对外界可见,大概是因为其身份很重要。乍看之下,似乎只有属性的获取端,但是如果 X 是可分配的,则情况并非如此。

Here we return a reference to the underlying X member, which allows both sides of the call site to observe changes initiated by the other. The X member is visible to the outside world, presumably because it's identity is important. It may at first glance look like there is only the "get" side of a property, but this is not the case if X is assignable.

 Foo f;
 f.x() = X { ... };

面向价值

class Foo
{
     X x_;
public:
     X x() const { return x_; }
     void x(X x) { x_ = std::move(x); }
}

在这里,我们返回 X 成员,并接受 copy 覆盖。以后任何一方的更改都不会传播。大概在这种情况下,我们只关心 x

Here we return a copy of the X member, and accept a copy to overwrite with. Later changes on either side do not propagate. Presumably we only care about the value of x in this case.

这篇关于如何编写C ++ getter和setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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