操作符在类外重载 [英] Operator overloading outside class

查看:140
本文介绍了操作符在类外重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种方法可以重载C ++类的操作符:

There are two ways to overload operators for a C++ class:

class Vector2
{
public:
    float x, y ;

    Vector2 operator+( const Vector2 & other )
    {
        Vector2 ans ;
        ans.x = x + other.x ;
        ans.y = y + other.y ;
        return ans ;
    }
} ;



课外



Outside class

class Vector2
{
public:
    float x, y ;
} ;

Vector2 operator+( const Vector2& v1, const Vector2& v2 )
{
    Vector2 ans ;
    ans.x = v1.x + v2.x ;
    ans.y = v1.y + v2.y ;
    return ans ;
}

(显然在C#中你只能使用外部类方法。

(Apparently in C# you can only use the "outside class" method.)

在C ++中,哪种方式更正确?哪一个是最好的?

In C++, which way is more correct? Which is preferable?

推荐答案

基本问题是你希望在左侧参数中执行转换操作员?如果是,请使用自由功能。

The basic question is "do you want conversions to be performed on the left-hand side parameter of an operator?". If yes, use a free function. If no, use a class member.

例如,对于字符串的运算符+(),我们希望执行转换,因此我们可以这样说:

For example, for operator+() for strings, we want conversions to be performed so we can say things like:

string a = "bar";
string b = "foo" + a;

其中执行转换以将char *foo转换为std :: string。因此,我们使字符串的运算符+()为一个自由函数。

where a conversion is performed to turn the char * "foo" into a std::string. So we make operator+() for strings into a free function.

这篇关于操作符在类外重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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