4-1 operator overloading of complex classes (sdutoj2677)

Source: Internet
Author: User
Http://acm.sdut.edu.cn/sdutoj/showproblem.php? PID = 2677 & cid = 1275 description

You can use this exercise to master the member Operator Overloading and friend Operator overloading.

It is required to define a plural class, And to reload addition and subtraction operators to meet the requirements for plural operations. The reload insertion operator (<) is used to output a plural value.

Input

The value of the object must be initialized when an object is created in the main function.

Output

There are 4 rows of output data, which respectively represent the values of A and B AND THEIR SUM and Difference values.

Sample Input
None
Sample output
a=3.2+4.5ib=8.9+5.6ia+b=12.1+10.1ia-b=-5.7-1.1i
Prompt
#include <iostream>using namespace std;class Complex{public:    Complex(double r,double i)    {        rm=r;        im=i;    }    friend Complex operator +(Complex &c1,Complex &c2);    friend Complex operator -(Complex &c1,Complex &c2);    void display();private:    double rm,im;};void Complex::display(){    cout<<"="<<rm;    if(im>=0) cout<<"+"<<im<<"i"<<endl;    else cout<<im<<"i"<<endl;}Complex operator+(Complex &c1,Complex &c2){    return Complex(c1.rm+c2.rm,c1.im+c2.im);}Complex operator-(Complex &c1,Complex &c2){    return Complex(c1.rm-c2.rm,c1.im-c2.im);}int main(){    Complex c1(3.2,4.5),c2(8.9,5.6);    Complex c3(0,0);    cout<<"a";    c1.display();    cout<<"b";    c2.display();    cout<<"a+b";    c3=c1+c2;    c3.display();    cout<<"a-b";    c3=c1-c2;    c3.display();    return 0;}

 

4-1 operator overloading of complex classes (sdutoj2677)

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.