CS Electrical And Electronics
@cselectricalandelectronics

Operations through global friend functions

All QuestionsCategory: Cpp LanguageOperations through global friend functions
Anonymous asked 3 years ago
1 Answers
Anonymous answered 3 years ago
#include <iostream>
class Complex {
int m_real;
int m_imag;

public:
Complex() {}

Complex(int real, int imag) : m_real(real), m_imag(imag) {}

void display() {
// print m_real, m_imag in a+ib format
}
friend Complex add(const Complex &r1, const Complex &r2);
friend Complex multiply(const Complex &r1, const Complex &r2);
friend Complex subtract(const Complex &r1, const Complex &r2);
friend bool equals(const Complex &r1, const Complex &r2);
};
Complex add(const Complex &r1, const Complex &r2) { // c1.add(c2)
int treal = r1.m_real + r2.m_real; // this->m_real + ref.m_real
int timag = r1.m_imag + r2.m_imag;
//Complex temp(treal, timag);
//return temp;
return Complex(treal,timag);
}

Complex multiply(const Complex &r1, const Complex &r2) {
// TODO
}

Complex subtract(const Complex &r1, const Complex &r2) {
// TODO
}

bool equals(const Complex &r1, const Complex &r2) { // c1.equals(c2)
return r1.m_real == r2.m_real && r1.m_imag == r2.m_imag;
}

int main() {
Complex c1(2, 3);
Complex c2(4, 5);
Complex c3, c4, c5;

c3 = add(c1, c2);

c5 = multiply(c1, c2);

if (equals(c1, c2))
std::cout << "yes";
else
std::cout << "no";

return 0;
}