Pages

Sunday, May 18, 2025

Complex Number Class with Subtraction Operator Overloading in OOPs (Assignment Question 1)

 #include <iostream>

using namespace std;



// Complex Number Substraction Code using Operator Overloading


class Complex {

private: 

    int real, img;


public:    

    Complex(int r, int i) {

        real = r;

        img = i;

        

    }

    

    void showNum() {

        cout << real << " - " << img << "i\n";

    }

    

    

    // Operator Overloading 

    void operator-(Complex &c2) {  // &c2 is value of reference..

    

        int resReal = this->real - c2.real; // result of real

        int resImg = this->img - c2.img; // result of image

        Complex c3(resReal, resImg); // taking both objects of resReal , resImg.

        c3.showNum(); // display the result

    }

    

};




int main()

{   

    Complex c1(2, 4);

    Complex c2(1, 2);

    

    c1.showNum();

    c2.showNum();

    

    c1-c2;

    

    return 0;

}

No comments:

Post a Comment

Stack using Linked List – Partial (University Exam Topic)

 #include <iostream> using namespace std; struct Node {     int data;     Node* next; }; class Stack {     Node* top; public:     Stac...