Перегрузка оператора умножения для разных типов
Дана задача: реализовать класс "Комплексное число", поля класса: действительная и мнимая части. Одним из методов класса должна быть перегрузка оператора умножения для двух комплексных чисел и для комплексного и вещественного числа. В классе действительная и мнимая части задаются переменными типа double.
Получилось создать класс с рабочим методом для перемножения двух комплексных чисел, приведу его код:
complex_number complex_number :: operator * (complex_number second_multiplier)
{
complex_number operation_result;
operation_result.Re = Re * second_multiplier.Re - Im * second_multiplier.Im;
operation_result.Im = Im * second_multiplier.Re + Re * second_multiplier.Im;
return operation_result;
}
Однако не совсем понимаю, как реализовать перегрузку для того, чтобы на вход можно было дать вещественное число, так как операции для него будут другими, да и тип параметра тоже, т. е. чтобы работало не только
complex_number a, b, c;
//... задание значений переменных a и b
c = a * b;
но и
c = a * 2.5;
Думаю, что нужно использовать шаблоны, но не представляю, как это реализовать.
Ответы (1 шт):
Реализация того, что я написал в комментарии.
class Complex
{
double re, im;
public:
Complex(double re = 0.0, double im = 0.0):re(re),im(im) {}
Complex(const Complex& c) = default;
~Complex() = default;
Complex& operator=(const Complex& c)
{
this->re = c.re; this->im = c.im;
return *this;
}
friend Complex operator+(const Complex&a, const Complex& b);
friend Complex operator-(const Complex&a, const Complex& b);
friend Complex operator*(const Complex&a, const Complex& b);
friend ostream& operator << (ostream& os, const Complex& b);
};
Complex operator+(const Complex&a, const Complex& b)
{
return Complex{a.re+b.re, a.im+b.im};
}
Complex operator-(const Complex&a, const Complex& b)
{
return Complex{a.re-b.re, a.im-b.im};
}
Complex operator*(const Complex&a, const Complex& b)
{
return Complex{a.re*b.re - a.im*b.im, a.im*b.re + a.re*b.im};
}
ostream& operator << (ostream& os, const Complex& b)
{
return os << "(" << b.re << "," << b.im << ")";
}
int main(int argc, const char * argv[])
{
Complex c{4,5}, d{2,1};
Complex a = c + 1;
Complex b = 2 + c;
cout << a << " " << b << endl;
a = c*d + 3*a + b*4;
cout << a << endl;
}