"Property" 类方法而不是 C++ 中的 getter 和 setter?

"Property"-like methods instead of getters & setters in C++?

情况:

class Person {
public:
     int& age();
     int age() const;
private:
     int m_age;
};

我不知道这是否像我想的那样有效,所以我的第一个问题是:

示例:

Person p;
p.age() = 15; //first method is called?
std::cout << p.age(); //second method?

我开始认为这完全是基于混合运算符重载和 const 方法的愚蠢行为,所以请问:有人可以启发我吗? :D

如果奇迹般地有效,我可以用它代替 getters 和 setters 还是这是一个糟糕的练习?

您的代码编译良好并按预期工作:

#include <iostream>

class Person {
public:
     int& age() { return m_age; }
     int age() const { return m_age; }
private:
     int m_age;
};

int main () {
    Person p;
    p.age() = 15; //first method is called?
    std::cout << p.age(); //second method?
}

See Live Demo


If miraculously this works, can I use this instead of getters & setters or this is a bad exercise? (emphasis mine)

不,这不能用作 setter 函数的真正替代品。
返回对成员变量的引用使客户端可以完全控制该成员变量,这不同于 setter like

void age(int newValue) {
    if(newValue > 150) {
         throw std::invalid_argument("You're older than 150? We don't believe that!");
    }
    m_age = newValue;
};

是也不是。

属性是隐藏函数的语法糖。所以是的。您可以编写一个 returns 引用的函数,并得到一些表面上看起来像 属性.

的东西

但考虑一下:属性 背后是一个 setter 函数,它可以(并且应该)做的不仅仅是简单地设置一个值。任何 setter 的要点是确保设置该值不会损害对象的状态。

通过将 setter 替换为 returns 对 private 成员的未受保护引用的函数,您正在剥离这条防线。调用者可以在他们认为合适的情况下使用该引用,但可能会损害对象。这可能很好,具体取决于成员的性质,但您也可以诚实。声明成员public,提高可读性,省去自己写函数的麻烦。

至于问题的 const 部分,您可以将 int& age() 看作是 int& age(Person * this)int age() const 作为 int age(const person * this)

在 OP 的示例中,age() 永远不会在常量 Person 上调用,因此没有理由调用 int age() const