Operator Overloading Example

Source: Internet
Author: User

Topic One: the addition of two complex numbers is accomplished without operator overloading. Generate complex object c1,c2, get c3=c1+c2, and print output C3.

#include <iostream>using namespacestd;classcomplex{ Public: Complex () {real=0; imag=0;} Complex (DoubleRDoublei): Real (R), Imag (i) {} complex Complex_add (complex&C2); voiddisplay (); Private:        DoubleReal,imag;}; Complex Complex::complex_add (Complex&C2)    {complex C; C.real=real+c2.real;//who calls is who's thisc.imag=imag+C2.imag; returnC;}voidComplex::d isplay () {cout<<"("<<real<<","<<imag<<")"<<Endl;}intMain () {Complex C1 (3.5,4.5), C2 (3.6,4.4), C3; C3=C1.complex_add (C2);    C3.display (); return 0;}
View Code

Operator Overloading:

function type operator operator name (formal parameter list);
The name of the operator+ operator, which can be interpreted as a function name

Complex complex::operator+ (complex &c2)
{ return complex (REAL+C2.REAL,IMAG+C2.IMAG); }

#include <iostream>using namespacestd;classcomplex{ Public: Complex () {real=0; imag=0;} Complex (DoubleRDoublei): Real (R), Imag (i) {} complexoperator+ (Complex &C2); voiddisplay (); Private:        DoubleReal,imag;}; Complex complex::operator+ (Complex & C2)//operator Overloading{    returnComplex (real+c2.real,imag+c2.imag);}voidComplex::d Isplay ()//Output{cout<<"("<<real<<","<<imag<<")"<<Endl;}intMain () {Complex C2 (3.6,4.4), C3; C3=complex (3.5,4.5)+C2;    C3.display (); return 0;}
View Code

Operator Overloading Example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.