what is the difference between overloading an operator inside or outside a class?
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;
}
成员operator+
要求LHS成为a
- 免费运营商要求LHS或RHS是b
而另一方可以转换为b
struct Foo {
Foo() {}
Foo(int) {}
Foo operator+(Foo const & R) { return Foo(); }
};
struct Bar {
Bar() {}
Bar(int) {}
};
Bar operator+(Bar const & L, Bar const & R) {
return Bar();
}
int main() {
Foo f;
f+1; // Will work - the int converts to Foo
1+f; // Won't work - no matching operator
Bar b;
b+1; // Will work - the int converts to Bar
1+b; // Will work, the int converts to a Bar for use in operator+
}
链接地址: http://www.djcxy.com/p/73054.html
上一篇: 用C#扩展方法重载操作符
下一篇: 在类内部或外部重载运算符有什么区别?