开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜