在类内部或外部重载运算符有什么区别?
在C++中,我知道有两种重载方法。我们可以在内部(如类a
)或外部(如类b
)重载它。但是,问题是,这两者在编译时或运行时有什么区别吗?
class a
{
public:
int x;
a operator+(a p) // operator is overloaded inside class
{
a temp;
temp.x = x;
temp.x = p.x;
return temp;
}
};
class b
{
public:
friend b operator+(b, b);
int x;
};
b operator+(b p1, b p2) // operator is overloaded outside class
{
p1.x += p2.x;
return p1;
}
In C++, i know there are two ways to overload. We can overload it inside (like class a
) or outside (like class b
). But, the question is, is there any difference between these two either in compile time or runtime or not?
class a
{
public:
int x;
a operator+(a p) // operator is overloaded inside class
{
a temp;
temp.x = x;
temp.x = p.x;
return temp;
}
};
class b
{
public:
friend b operator+(b, b);
int x;
};
b operator+(b p1, b p2) // operator is overloaded outside class
{
p1.x += p2.x;
return p1;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
成员
operator+
要求LHS为a
- 自由运算符要求LHS或RHS为b
另一边可转换为b
The member
operator+
requires the LHS to be ana
- The free operator requires LHS or RHS to be ab
and the other side to be convertible tob