在 C++ 中,是否可以从 class 成员函数 return class 的一个元素?

In C++ is it possible to return an element of the class from a class member function?

在 C++ 中,是否可以从 class 成员函数 return class 的一个元素?

namespace translation2d
{
    class translation2d
    {
        public:
           double x;
          double y;

        public:
            translation2d()
            {
                x=0;
                y=0;
            }

        public:
            translation2d translateBy(translation2d other); 
            //being interpreted as a constructor?
    }

    translation2d translation2d::translateBy(translation2d other)
    {//I need this member function to return an object of type translation2d
        x+=other.x;
        y+=other.y;
    }
};

当然可以,比如

struct Translation2d {
    double x, y;
    Translation2d(double x, double y) : x(x), y(y) {}
    Translation2d translate_by(const Translation2d& other) {
        return Translation2d(x + other.x, y + other.y);
    }
};

6502回答正确,代码工整

为了清楚起见,我只是想提供一个修复程序,尽量减少对原始代码的更改:

translation2d translation2d::translateBy(translation2d other)
{
    translation2d copy = *this;

    copy.x += other.x;
    copy.y += other.y;

    return copy;
}

想法是:

  1. 创建 "current" 对象的副本,以免影响原始对象(您不希望那样)
  2. Return 使用 other
  3. 中的数据调整后的副本

换句话说,我们可以避免再次复制参数,因为您已经按值传递了它:

translation2d translation2d::translateBy(translation2d copy)
{
    copy.x += this->x;
    copy.y += this->y;

    return copy;
}

…虽然我希望编译器在现实中为您做这件事,但我发现这个版本的代码更难阅读。请参阅此答案的最后一部分,了解避免额外副本的其他方法(假设您倾向于担心它)。


此函数的另一个版本实际上会翻译 当前 对象而不是 return 一个新对象:

translation2d& translation2d::translateBy(translation2d other)
{
    this->x += other.x;
    this->y += other.y;

    return *this;
}

请注意,我仍然 return 一些东西,而不是 void;在本例中,我遵循了 return 引用当前对象的约定,这有助于将多个修改链接到同一对象。您会在运算符重载中发现很多这种模式。

从技术上讲,this-> 是不必要的,但它使函数更容易理解。


请注意,6502 将函数更改为通过 const-reference 获取 other,这通常是个好主意,您也应该考虑这样做(尽管复制两个 double 非常便宜,以至于它可能不值得间接访问)。