Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Operator overloading

From Wikipedia, the free encyclopedia
Feature of some programming languages

Polymorphism
Ad hoc polymorphism
Parametric polymorphism
Subtyping

Incomputer programming,operator overloading, sometimes termedoperatorad hoc polymorphism, is a specific case ofpolymorphism, where differentoperators have different implementations depending on their arguments. Operator overloading is generally defined by aprogramming language, aprogrammer, or both.

Rationale

[edit]

Operator overloading issyntactic sugar, and is used because it allows programming using notation nearer to the target domain[1] and allows user-defined types a similar level of syntactic support as types built into a language. It is common, for example, in scientific computing, where it allows computing representations of mathematical objects to be manipulated with the same syntax as on paper.

Operator overloading does not change theexpressive power of a language (with functions), as it can be emulated using function calls. For example, consider variablesa,b andc of some user-defined type, such asmatrices:

a + b * c

In a language that supports operator overloading, and with the usual assumption that the* operator has higherprecedence than the+ operator, this is a concise way of writing:

Add(a, Multiply(b, c))

However, the former syntax reflects common mathematical usage.

Examples

[edit]

In this case, the addition operator is overloaded to allow addition on a user-defined typeTime inC++:

Timeoperator+(constTime&lhs,constTime&rhs){Timetemp=lhs;temp.seconds+=rhs.seconds;temp.minutes+=temp.seconds/60;temp.seconds%=60;temp.minutes+=rhs.minutes;temp.hours+=temp.minutes/60;temp.minutes%=60;temp.hours+=rhs.hours;returntemp;}

Addition is abinary operation, which means it has twooperands. In C++, the arguments being passed are the operands, and thetemp object is the returned value.

The operation could also be defined as a class method, replacinglhs by the hiddenthis argument; However, this forces the left operand to be of typeTime:

// The "const" right before the opening curly brace means that `this` is not modified.TimeTime::operator+(constTime&rhs)const{Timetemp=*this;// `this` should not be modified, so make a copy.temp.seconds+=rhs.seconds;temp.minutes+=temp.seconds/60;temp.seconds%=60;temp.minutes+=rhs.minutes;temp.hours+=temp.minutes/60;temp.minutes%=60;temp.hours+=rhs.hours;returntemp;}

Note that aunary operator defined as a class method would receive no apparent argument (it only works fromthis):

boolTime::operator!()const{returnhours==0&&minutes==0&&seconds==0;}

The less-than (<) operator is often overloaded to sort a structure or class:

classIntegerPair{private:intx;inty;public:explicitIntegerPair(intx=0,inty=0):x{x},y{y}{}booloperator<(constIntegerPair&p)const{if(x==p.x){returny<p.y;}returnx<p.x;}};

Like with the previous examples, in the last example operator overloading is done within the class. In C++, after overloading the less-than operator (operator<),standard sorting functions can be used to sort some classes.

Starting inC++20 with the introduction of thethree-way comparison operator (operator<=>), all the order operators can be defined by just defining that operator. The three-way comparison operator exists in many languages, includingC++,Python,Rust,Swift, andPHP. Other languages, such asJava andC# instead use a methodComparable.compareTo().

importstd;usingstd::strong_ordering;classIntegerPair{private:intx;inty;public:explicitIntegerPair(intx=0,inty=0):x{x},y{y}{}// can be auto-generated with = default;strong_orderingoperator<(constIntegerPair&p)const{if(strong_orderingcmp=x<=>p.x;cmp!=strong_ordering::equal){returncmp;}returny<=>p.y;}};

Criticisms

[edit]

Operator overloading has often been criticized[weasel words][2] because it allows programmers to reassign the semantics of operators depending on the types of their operands. For example, the use of the<< operator inC++a<<b shifts the bits in the variablea left byb bits ifa andb are of an integer type, but ifa is an output stream then the above code will attempt to write ab to the stream. Because operator overloading allows the original programmer to change the usual semantics of an operator and to catch any subsequent programmers by surprise, it is considered good practice to use operator overloading with care (the creators ofJava decided not to use this feature,[3] although not necessarily for this reason[original research?]).

Another, more subtle, issue with operators is that certain rules from mathematics can be wrongly expected or unintentionally assumed. For example, thecommutativity of + (i.e. thata + b == b + a) does not always apply; an example of this occurs when the operands are strings, since + is commonly overloaded to perform a concatenation of strings (i.e."bird" + "song" yields"birdsong", while"song" + "bird" yields"songbird"). A typical counter[citation needed] to this argument comes directly from mathematics: While + is commutative on integers (and more generally any complex number), it is not commutative for other "types" of variables. In practice, + is not even alwaysassociative, for example with floating-point values due to rounding errors. Another example: In mathematics, multiplication is commutative for real and complex numbers but not commutative inmatrix multiplication.

Catalog

[edit]

A classification of some common programming languages is made according to whether their operators are overloadable by the programmer and whether the operators are limited to a predefined set.

OperatorsNot overloadableOverloadable
New definable[4]
Limited set

Timeline of operator overloading

[edit]

1960s

[edit]

TheALGOL 68 specification allowed operator overloading.[36]

Extract from the ALGOL 68 language specification (page 177) where the overloaded operators ¬, =, ≠, andabs are defined:

10.2.2. Operations on Boolean Operandsa)op ∨ = (bool a, b)bool:( a |true | b );b)op ∧ = (bool a, b)bool: ( a | b |false );c)op ¬ = (bool a)bool: ( a |false |true );d)op = = (bool a, b)bool:( a∧b ) ∨ ( ¬b∧¬a );e)op ≠ = (bool a, b)bool: ¬(a=b);f)opabs = (bool a)int: ( a | 1 | 0 );

Note that no special declaration is needed tooverload an operator, and the programmer is free to create new operators. For dyadic operators their priority compared to other operators can be set:

priomax = 9;opmax = (int a, b)int: ( a>b | a | b );op++ = (refint a )int: ( a +:= 1 );

1980s

[edit]

Ada supports overloading of operators from its inception, with the publication of the Ada 83 language standard. However, the language designers chose to preclude the definition of new operators. Only extant operators in the language may be overloaded, by defining new functions with identifiers such as "+", "*", "&" etc. Subsequent revisions of the language (in 1995 and 2005) maintain the restriction to overloading of extant operators.

InC++, operator overloading is more refined than inALGOL 68.[37]

1990s

[edit]

Java language designers atSun Microsystems chose to omit overloading.[38][39][40] When asked about operator overloading, Brian Goetz ofOracle responded "Value types first, then we can talk about it.", suggesting that it could potentially be added afterProject Valhalla.[41]

Python allows operator overloading through the implementation of methods with special names.[42] For example, the addition (+) operator can be overloaded by implementing the methodobj.__add__(self, other).

Ruby allows operator overloading as syntactic sugar for simple method calls.

Lua allows operator overloading as syntactic sugar for method calls with the added feature that if the first operand doesn't define that operator, the method for the second operand will be used.

2000s

[edit]

Microsoft added operator overloading toC# in 2001 and toVisual Basic .NET in 2003. C# operator overloading is very similar in syntax to C++ operator overloading:[43]

publicclassFraction{privateintnumerator;privateintdenominator;// ...publicstaticFractionoperator+(Fractionlhs,Fractionrhs)=>newFraction(lhs.numerator*rhs.denominator+rhs.numerator*lhs.denominator,lhs.denominator*rhs.denominator);}

Scala treats all operators as methods and thus allows operator overloading by proxy.

2010s

[edit]

InRaku, the definition of all operators is delegated to lexical functions, and so, using function definitions, operators can be overloaded or new operators added. For example, the function defined in theRakudo source for incrementing a Date object with "+" is:

multiinfix:<+>(Date:D$d,Int:D$x) {Date.new-from-daycount($d.daycount +$x)}

Since "multi" was used, the function gets added to the list ofmultidispatch candidates, and "+" is only overloaded for the case where the type constraints in the function signature are met.While the capacity for overloading includes+,*,>=, thepostfix and termi, and so on, it also allows for overloading various brace operators:[x, y],x[y],x{y}, andx(y).

Kotlin has supported operator overloading since its creation by overwriting specially named functions (likeplus(),inc(),rangeTo(), etc.)[44]

dataclassPoint(valx:Int,valy:Int){operatorfunplus(other:Point):Point{returnPoint(this.x+other.x,this.y+other.y)}}

Because both Kotlin and Java compile to.class, when converted back toJava this will just be represented as:

publicclassPoint{// fields and constructor...publicPointplus(Pointother){returnnewPoint(this.x+other.x,this.y+other.y);}}

Operator overloading inRust is accomplished by implementing thetraits instd::ops.[45]

usestd::ops::Add;#[derive(Debug)]structPoint{x:i32,y:i32}implPoint{pubfnnew(x:i32,y:i32)->Self{Point{x,y}}}implAddforPoint{typeOutput=Point;fnadd(self,other:Point)->Point{Point{x:self.x+other.y,y:self.y+other.y}}}fnmain(){letp1:Point=Point::new(1,2);letp2:Point=Point::new(3,4);letsum:Point=p1+p2;println!("Sum of p1 and p2: {:?}",sum);}

See also

[edit]

References

[edit]
  1. ^Stroustrup, Bjarne."Operator Overloading".C++ FAQ. Archived fromthe original on 14 August 2011. Retrieved27 August 2020.
  2. ^Fisher, Charles N. (2008)."Issues in Overloading"(PDF).University of Wisconsin–Madison.
  3. ^"No more operator overloading".The Java Language Environment.Oracle Corporation.
  4. ^Completely new operators can be added.
  5. ^"Predicate op/3".
  6. ^"Bertrand Meyer: Basic Eiffel language mechanisms".se.ethz.ch. Retrieved7 April 2021.
  7. ^"Operator functions in F90".www.mathcs.emory.edu. Archived fromthe original on 11 August 2021. Retrieved7 April 2021.
  8. ^Introduced in Fortran 90.
  9. ^Smith, Chris (9 October 2012).Programming F# 3.0: A Comprehensive Guide for Writing Simple Code to Solve Complex Problems. O'Reilly Media, Inc.ISBN 978-1-4493-2604-3.
  10. ^Type classes instead of overloading.
  11. ^"Operator Overloading in Julia".geeksforgeeks.org. Retrieved14 March 2025.
  12. ^"Operators - R in a Nutshell, 2nd Edition [Book]".www.oreilly.com. Retrieved7 April 2021.
  13. ^"Operators".Tour of Scala.
  14. ^Hunt, John (6 December 2012).Smalltalk and Object Orientation: An Introduction. Springer Science & Business Media.ISBN 978-1-4471-0961-7.
  15. ^"Swift: Advanced Operators".
  16. ^"Why does Go not support overloading of methods and operators?". Retrieved4 September 2011.
  17. ^"Introduction".freepascal.org. Retrieved30 September 2020.
  18. ^"Operator Overloads".GitHub. Retrieved28 September 2018.
  19. ^"6.6 Overloading of Operators".Annotated Ada Reference Manual.
  20. ^Drayton, Peter; Albahari, Ben; Neward, Ted (2003).C# in a Nutshell. O'Reilly Media, Inc.ISBN 978-0-596-00526-9.
  21. ^"C++ Operator Overloading".
  22. ^"Operator Overloading - D Programming Language".dlang.org. Retrieved10 October 2020.
  23. ^"A tour of the Dart language".dart.dev. Retrieved30 September 2020.
  24. ^"The Apache Groovy programming language - Operators".groovy-lang.org. Retrieved30 September 2020.
  25. ^"Operator overloading".Kotlin. Retrieved24 June 2018.
  26. ^"Metamethods Tutorial".Lua-users Wiki.
  27. ^"Implementing Operators for Your Class". Archived fromthe original on 14 June 2024. Retrieved1 October 2013.
  28. ^"Operator Overloading".Free Pascal Manual. Retrieved1 December 2014.
  29. ^"Operator Overloading".Delphi Manual. Retrieved1 December 2014.
  30. ^"PHP magic methods overriding class properties". Archived fromthe original on 4 March 2016. Retrieved7 April 2015.
  31. ^Orwant, Jon (4 November 2002).Computer Science & Perl Programming: Best of The Perl Journal. O'Reilly Media, Inc. pp. 347–.ISBN 978-0-596-00310-4.
  32. ^"3. Data Model".The Python Language Reference.
  33. ^"Methods".Official Ruby FAQ.
  34. ^"Operator Overloading".Rust By Example.
  35. ^"How to: Define an Operator (Visual Basic)". 15 September 2021.
  36. ^van Wijngaarden, A.; Mailloux, Barry J.;Peck, John E. L.;Koster, Cornelis H. A.; et al. (August 1968)."Report on the Algorithmic Language ALGOL 68, Section 10.2.2"(PDF). Retrieved1 April 2007.
  37. ^Stroustrup, Bjarne."A History of C++: 1979−1991"(PDF). p. 12. Retrieved1 April 2007.
  38. ^"FAQ Question 6.9: Why isn't there operator overloading?".The comp.lang.java FAQ List.
  39. ^"java.sun.com". Archived fromthe original on 7 March 2009. Retrieved26 March 2009.
  40. ^Holzner, Steven (2001).C++: Black Book. Scottsdale, Arizona: Coriolis Group. p. 387.ISBN 1-57610-777-9.One of the nicest features of C++ OOP is that you can overload operators to handle objects of your classes (you can't do this in some other OOP-centric languages, like Java).
  41. ^@BrianGoetz (11 January 2017)."Value types first, then we can talk about it" (Tweet) – viaTwitter.
  42. ^"3. Data Model, Special method names".The Python Language Reference.
  43. ^"Operator overloading - predefined unary, arithmetic, equality, and comparison operators".learn.microsoft.com. Microsoft Learn. 13 June 2025.
  44. ^"Operator overloading Kotlin".kotlinlang.org. JetBrains s.r.o. Retrieved15 October 2025.
  45. ^"Operator Overloading - Rust By Example".doc.rust-lang.org. Rust Programming Language. Retrieved15 October 2025.
Authority control databasesEdit this at Wikidata
Retrieved from "https://en.wikipedia.org/w/index.php?title=Operator_overloading&oldid=1331821751"
Category:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp