开发者

What is Operator overloading? Is operator overloading a specific feature to C++ and not available in Java

开发者 https://www.devze.com 2023-01-21 10:53 出处:网络
Please explain in detail with examples. T开发者_如何学Chank youOperator overloading is a feature where the language allows you to define operators for your own types, so that you can write e.g. o1 + o

Please explain in detail with examples. T开发者_如何学Chank you


Operator overloading is a feature where the language allows you to define operators for your own types, so that you can write e.g. o1 + o2 where o1 and o2 are instances of your own type, instead of built-in types.

Operator-overloading is not specific to C++, but it's not available in java. Here's an example in Python:

class Vector3D():
  def __init__(self, x, y, z):
    self.x = x
    self.y = y
    self.z = z
  def __repr__(self):
    return "Vector<%f,%f,%f>" % (self.x, self.y, self.z)
  def __add__(self, other):
    return Vector3D(self.x + other.x,
                    self.y + other.y,
                    self.z + other.z)

a = Vector3D( 1, 2, 3)
b = Vector3D(-1,-2,-3)
print a+b # Vector<0.000000,0.000000,0.000000>
0

精彩评论

暂无评论...
验证码 换一张
取 消