Search code examples
c++object

return float when + class


I was trying to take float + objected class and have the result return as float, however, my code just does not work. I am pretty confused. I have added that overload function as a friend to the class. could anyone explain it to me? With the best regards

#include <iostream>
#include <cstdint>
using namespace std;
#define MAX_NUM_SENSORS 5
enum { INVALID, TEMPERATURE, HUMIDTY };

// The 'Sensors' structure describes a single sensor, it's type and current value.
//   type - describes the type of sensor 0 (INVALID), 1 (TEMPERATURE), 2 (HUMIDITY)
//   value - the current value of the sensor.
//   valid - set to TRUE if the sensor is valid, should default to FALSE until set up.
class Sensors
{
public:
    friend ostream& operator <<(ostream&, const Sensors&);
    friend float operator+ (float,const Sensors&);
private:
    int type;
    float value;
    bool valid = false;
};
ostream& operator<<(ostream& OutStream, const Sensors& OutComp)
{
    OutStream << " Type: " << (OutComp.type == TEMPERATURE ? "Temperature" : "Humidity");
    OutStream << " Value: " << OutComp.value << endl;
    return OutStream;
}
float operator+ (float adding, const Sensors& added)
{
    float sum;
    sum = added.value + adding;
    return sum;
}
int main()
{
    Sensors tested();
    float m = 1.2 + tested;
    cout << m;
    return 1;
}

Solution

  • I ran your code in godbolt

    There is some kind of simple fixes.

    int main()
    {
        Sensors tested();
        //            ^--- remove this parenthesis (or use braces, it's ambigious)
        float m = 1.2 + tested;
        //        ^----- This is a double, change this to "1.2f"
        cout << m;
        return 1;
    }
    

    Decimal values in code is double by default, you need to add the postfix f to specify that it is a float. Or you could add a definition of operator + with double as a parameter.

    Here is a compiling version of your code