Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ type qualifier problem

As part of my Computer Software Development degree, one of my labs consists of creating a calculator class template and a fraction class.

The problem is with my fraction class. My task is now to overload the plus operator to allow two fractions to be added together.

Fraction.cpp:

#include "Fraction.h"

const Fraction Fraction::operator+ (const Fraction &rhs) const
{
    return Fraction(_num * rhs.GetDen() + (rhs.GetNum() * _den), _den * rhs.GetDen());
}

Fraction.h

#pragma once

class Fraction
{
    public:
        Fraction(const int &num, const int &den) : _num(num), _den(den) {}
        ~Fraction(void) {}
        const int GetNum(void) { return _num; }
        const int GetDen(void) { return _den; }
        const Fraction operator+ (const Fraction &rhs) const;

    private:
        const int _num, _den;
};

Visual Studio complains that my fraction accessors cannot 'convert this pointer from const fraction to fraction &'. I'm completely baffled.

like image 873
Lee Avatar asked May 11 '11 18:05

Lee


2 Answers

You need to qualify your accessors as const too:

int GetNum(void) const { return _num; }

BTW, qualifying the return type as const int does not really make sense, it will be an int anyway. Your compiler should emit a warning.

like image 63
Gunther Piez Avatar answered Nov 11 '22 08:11

Gunther Piez


You GetNum and GetDen accessor methods are not declared as "const", so they cannot be called within the operator+ against const Fractions.

like image 38
DataGraham Avatar answered Nov 11 '22 09:11

DataGraham