如何在 return 常量引用的 class 成员上正确调用 setter

How do I properly call setters on a return constant referenced class member

我的问题是我正在尝试访问 class 成员常量引用的 none 常量 setter,导致错误 (C2662)。如果我将值设置为可变的,并且 setter 常量,那么我没问题,但我读到你应该避免这样做,但找不到另一种方法来做到这一点。

vector2D的定义:

class vector2D {
    int _x;
    int _y;
public:
    vector2D() :
    _x(0),
    _y(0) {};

    // Getters
    int xGet() { return _x;};
    int yGet() { return _y;};

    // Setters
    void xSet(int x) {
        if (x > 100) {
            _x = 100;
            return;

        } else if (x < 0) {
            _x = 0;
            return;

        } else {
            _x = x;
            return;
        }
    };

    void ySet(int y) {
        if (y > 100) {
            _y = 100;
            return;

        } else if (y < 0) {
            _y = 0;
            return;

        } else {
            _y = y;
            return;
        }
    };
};

npc定义:

class npc {
    vector2D _position;
public:
    npc () {};
    const vector2D& positionGet() const{
        return _position;
    };
};

main.cpp :

main () { 
    vector2D myPos;
    myPos.xSet(2);    //Okay

    npc myGuy;
    myGuy.positionGet().xSet(2);    //C2662

    return 0;
}

我尝试过的:

我试图创建 xSet/ySet 常量函数,但是这给了我一个错误(表达式必须是一个可修改的左值),这是有道理的。我一直在阅读有关这方面的文章,但正确的方法一直不清楚。

我试着让 x/y 可变,这样我就可以让 setter 函数保持不变,这确实消除了错误,但后来我读到很多人说不行要使用可变的,还有什么其他方法可以做到这一点?

我还尝试使“_position”none 的 returned 值保持不变,但这不是不安全吗???

注意:我也在努力使我的问题更好,所以请 message/leave 评论我如何更好地提出这个问题:D


编辑:我发现了什么

所以很多人的建议是 return 一个 none ‘_position’ 的常量引用,但我发现的问题是你可以直接给return编辑参考。

vector2D newPos;
myGuy.positionGet() = newPos;

这很糟糕,因为 returned 值是私有成员,因此不能直接赋值。 这也很糟糕,因为如果 npc 通过引用传递给函数,然后完成上述操作,一旦它超出范围,它就会调用 vector2D 上的析构函数。

void functTest (npc & ch1) {
    vector2D c1;
    ch1.positionGet() = c1;

    return;
}

出于某种原因也破坏了 ch1._position ???

如果您希望 getter 成为 return 可变引用,那么 这样做

您想调用 positionGet() 并获取一个您可以修改的对象。

所以不要成功 const

vector2D& positionGet() {
    return _position;
};

简单如.

您可以为职位提供可变接口和常量接口:

class npc {
    vector2D _position;
public:
    npc () {};
    const vector2D& position() const { return _position; };
    vector2D& mutable_position() { return _position; };
};

是的,当您调用 mutable_position() 时,将返回对私有成员的引用,但如果这是程序员的意图(如在 "mutable_" 中的显式使用所示)调用),那么应该没问题。