简体   繁体   中英

addition and subtraction of two numbers using operator overloading

#include<iostream>

using namespace std;

class add
{
private: int a,b;
public: add(int x=0)
        {
            a=x;
        }
        add operator+(add const &c)         // sub operator-(sub const &c)
        {                                   //{
            add sum;                        //      sub diff;
            sum.a=a+c.a;                    //      diff.a=a-c.a;
            return sum;                     //      return diff
        }                                   //}
        void print()
        {
            cout<<"sum: "<<a;
        }
};

int  main()
{
add a1(10),a2(5);                           //sub s1(10),s2(5);
add a3=a1+a2;                               // sub s3=s1-s2;
a3.print();                                 // s3.print();
return 0;
}

Here I've written seperately but what to do if I need to do both in a single code? I want a C++ code to perform them simultaneously

You can define any reasonable combination of:

Foo operator+(arg);
Foo operator-(arg);
Foo operator*(arg);
Foo operator/(arg);

And the arg can be another Foo or some other type entirely. For instance:

#include <iostream>

using namespace std;

class Operators {
public:
    Operators() = default;
    Operators(int v) : value(v) {}

    Operators operator+(const Operators &other) {
        return Operators{value + other.value};
    }

    Operators operator+(const int byValue) {
        return Operators{value + byValue};
    }

    Operators operator-(const Operators &other) {
        return Operators{value - other.value};
    }

    Operators operator-(const int byValue) {
        return Operators{value - byValue};
    }

    Operators operator*(const Operators &other) {
        return Operators{value * other.value};
    }

    Operators operator/(const Operators &other) {
        return Operators{value / other.value};
    }

    int value = 0;
};

int main(int, char **) {
    Operators first{10};
    Operators second{20};

    Operators result1 = first + second;
    Operators result2 = first * second;
    Operators result3 = first * 3;
    Operators result4 = second / 2;

    cout << "first + second == " << result1.value << endl;
    cout << "first * second == " << result2.value << endl;
    cout << "first * 3      == " << result3.value << endl;
    cout << "first / 2      == " << result4.value << endl;
}

first + second == 30 first * second == 200 first * 3 == 30 first / 2 == 10

You'll see I overwrote operators that take two Operators objects, but I also wrote a few that take an integer argument, too.

I compiled and ran that with:

g++ --std=c++17 Whatever.cpp -o Whatever && Whatever

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM