+ =类的正则形式+运算符 [英] Canonical form of += operator for classes

查看:215
本文介绍了+ =类的正则形式+运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个好主意,使一个类非成员非朋友尽可能多的接口,我刚刚意识到,对于我的3D矢量类'Vector3',我可以移动+ =, - =等等,所以只剩下构造函数和复制赋值操作符。



问题是:这个操作符应该是什么样子?我已经看到许多其他运算符的规范形式,并遵循他们的建议,但我还没有看到这些运算符的规范形式。我已经给出了我认为应该在下面。



第二个问题是:这些操作符甚至是什么?

  

class Vector3 {
public:
Vector3& operator + =(const Vector3& rhs);
float x,y,z;
};

Vector3& Vector3 :: operator + =(const Vector3& rhs){
x + = rhs.x;
y + = rhs.y;
z + = rhs.z;

return * this;
}

到目前为止我改变了什么:

 类Vector3 {
public:
float x,y,z;
};

Vector3& operator + =(Vector3& lhs,const Vector3& rhs){
lhs.x + = rhs.x;
lhs.y + = rhs.y;
lhs.z + = rhs.z;

return lhs;
}


解决方案



顺便说一下,当你来到运算符+时,通常用+ =来实现。 (创建一个lhs的副本,然后调用lhs + = rhs并返回结果)



不知道你是否已经知道这个技巧,你关心的是实现这些操作符的规范方法,它不能伤害提及它。 :)


I know that it's a good idea to make as much of the interface of a class non-member non-friend as possible, and I've just realised that for my 3D vector class, 'Vector3', I can move the +=, -= and so on operators out of the class, leaving just constructors and the copy assignment operator.

The question is: what should this operator look like? I've seen canonical forms of plenty of other operators and have followed their advice, but I haven't seen canonical forms of these operators. I've given what I think it should be below.

The secondary question is: what are these operators even called? Arithmetic assignment operators?

The (relevant) code before:

class Vector3 {
public:
    Vector3& operator+=(const Vector3& rhs);
    float x, y, z;
};

Vector3& Vector3::operator+=(const Vector3 &rhs) {
    x += rhs.x;
    y += rhs.y;
    z += rhs.z;

    return *this;
}

What I've changed it to so far:

class Vector3 {
public:
    float x, y, z;
};

Vector3& operator+=(Vector3& lhs, const Vector3& rhs) {
    lhs.x += rhs.x;
    lhs.y += rhs.y;
    lhs.z += rhs.z;

    return lhs;
}

解决方案

What you have looks good to me.

By the way, when you come to the operator+, it is common to implement that in terms of +=. (create a copy of lhs, and then call lhs += rhs and return the result)

Don't know if you're already aware of this trick, but since you're concerned about canonical ways to implement these operators, it can't hurt to mention it. :)

这篇关于+ =类的正则形式+运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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