当从 setter 方法返回 *this 时,对象变得不可变 [英] Object becomes immutable when returning *this from a setter method

查看:29
本文介绍了当从 setter 方法返回 *this 时,对象变得不可变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在了解这个指针,它包含正在调用该函数的当前对象的地址.但是当我从成员函数返回当前对象时,我对这个指针有疑问.

I was learning about this pointer that it contains the address of the current object that is invoking the function. But I have a doubt regarding this pointer when I am returning the current object from the member function.

#include<bits/stdc++.h>
using namespace std;
class Point
{
    private:
        int x,y;
    public:
        Point(int x,int y)
        {
            this->x = x;
            this->y = y;
            //cout<<this<<endl;                 
        }
        Point setX(int x)
        {
            this->x = x;
            //cout<<this<<endl;
            return *this;
        }
        
        Point setY(int y)
        {
            this->y = y;
            //cout<<this<<endl;
            return *this;
        }
        int getX()
        {
            return x;
        }                    
        int getY()
        {
            return y;
        }
};                                                           
int main()
{
    Point p(10,20);
    cout<<p.getX()<<" "<<p.getY()<<endl;
    p.setX(1000).setY(2000);
    cout<<p.getX()<<" "<<p.getY();
    return 0;
}

为什么 p.setX(1000).setY(2000) 只修改 x 的值,而不修改 y 的值?为什么在第二个 cout 语句答案是 1000 20 但它应该是 1000 2000?

Why p.setX(1000).setY(2000) is only modifying the value of x, not y? Why in the second the cout statement answer is 1000 20 but it should be 1000 2000?

推荐答案

原因是你的 setX()setY() 方法返回一个 Point - 他们返回对象的副本.因此,您的 setY() 设置了您点的临时副本的 y 成员,而不是原始点的成员.

The reason is that your setX() and setY() methods return a Point - they return a copy of your object. So your setY() sets the y member of the temporary copy of your point, not of the original point.

您可以通过更改以下签名来纠正此问题:

You could rectify this by changing the signatures from:

Point setX(int x)

到:

Point& setX(int x)

setY() 类似.您会注意到返回类型现在是 Point& - 对 Point 对象的引用.

and similarly for setY(). You'll note the return type is now Point& - a reference to a Point object.

但是请注意,您的类的 getter 和 setter 方法有效地允许将 xy 视为公共对象.因此,除非您打算用坐标的一些隐式表示来潜在地替换它们(例如,具有角度 + 距原点的距离),在这种情况下,setter 和 getter 变得有趣 - 您还可以考虑将您的类简化为:

Note, however, that your class' getter and setter method effectively allow treating x and y like public objects. So, unless you plan on potentially replacing them with some implicit representation of the coordinates (e.g. having angle + distance from the origin), in which case the setters and getters become interesting - you could also consider simplifying your class into:

struct Point { int x, y; }

简单的设计通常是合适的.

the simple design is often appropriate.

最后,与您的具体问题无关,您的代码以几行不合时宜的行开头...

Finally, unrelated to your specific question, your code starts with a few inopportune lines...

这篇关于当从 setter 方法返回 *this 时,对象变得不可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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