有两种方法可以重载 C++ 类的运算符:
课堂内
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 ;
}
} ;
课外
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# 中你只能使用“外部类”方法。)
在C++中,哪种方式更正确?哪个更可取?
基本问题是“您希望对运算符的左侧参数执行转换吗?”。如果是,请使用免费函数。如果不是,请使用班级成员。
例如,对于operator+()
对于字符串,我们希望执行转换,这样我们就可以这样说:
string a = "bar";
string b = "foo" + a;
其中执行转换以将char * "foo"
进入一个std::string
。所以,我们使operator+()
将字符串转换为自由函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)