Vladimir Orlov Vladimir Orlov - 11 days ago 6
C++ Question

Overload operator +

Simple question: I have a class simple_fraction and want to overload operator "+". Complilator returns error "operator + local function definition is illegal.

#pragma once
#include <iostream>

class simple_fraction {
private:
int numerator; //числитель
int denominator; //знаменатель
public:
simple_fraction(int numerator, int denominator) {

//определение основных математических операций для простой дроби
double operator+ (double val) { return number + val; } //сложение
}}

int main()
{
simple_fraction fr(2, 3);
double sum = fr + 10; //сумма
}


what is wrong with that?

Answer

You have:

simple_fraction(int numerator, int denominator) {

   //определение основных математических операций для простой дроби
   double operator+ (double val) { return number + val; } //сложение
}}

which makes the operator+ function a local function inside the constructor, which is not allowed. You need to finish the constructor definition before the operator+ function. And you also need to correct the operand inside the operator+

simple_fraction(int numerator, int denominator) : numerator(numerator),
                                                  denominator(denominator){}

double operator+ (double val) { return numerator + val; }

PS

That implementation of operator+ does not sound right. Perhaps you meant:

double operator+ (double val) { return 1.0*numerator/denominator + val; }