I'm learning C++, and I'm a little unclear on how inheritance and operator overloading work, so I might very well be doing something silly here.
I have a base class that defines some very basic operations for representing units of measurement:
#pragma once
class UnitOfMeasure
{
public:
UnitOfMeasure(void) : mAmount(0) {}
UnitOfMeasure(double amount) : mAmount(amount) { }
~UnitOfMeasure() {}
void SetAmount(double amount) { mAmount = amount; }
UnitOfMeasure& operator+=(const UnitOfMeasure& rhs)
{
mAmount += rhs.mAmount;
return *this;
}
friend bool operator==(const UnitOfMeasure&, const UnitOfMeasure&);
protected:
double mAmount;
};
bool operator==(const UnitOfMeasure& lhs, const UnitOfMeasure &rhs)
{
return rhs.mAmount == lhs.mAmount;
}
Subclasses then implement specific conversions like this:
#pragma once
#include "UnitOfMeasure.h"
class Temperature : public UnitOfMeasure
{
public:
enum TemperatureUnit { CELSIUS, FAHRENHEIT };
Temperature(void) { }
Temperature(double amount, TemperatureUnit units=CELSIUS) { SetAmount(amount, units); }
~Temperature(void) {};
void SetAmount(double amount, TemperatureUnit units=CELSIUS)
{
switch(units)
{
case CELSIUS: { mAmount = amount; break; }
case FAHRENHEIT: { mAmount = (amount - 32) / 1.8; break; }
}
}
double Fahrenheit() { return 32 + (mAmount * 1.8); }
double Celsius() { return mAmount; };
};
In my sample program, I'm storing instances of Temperature in a list, and this is where things start to get weird. When all the code is contained in the .h file, everything is just fine. I can compile and run successfully. However, the compiler complains when I break Temperature's code out into a separate .cpp file. I get these messages:
1> Temperature.cpp
1>Temperature.obj : error LNK2005: "bool __cdecl operator==(class UnitOfMeasure const &,class UnitOfMeasure const &)" (??8@YA_NABVUnitOfMeasure@@0@Z) already defined in BadComparison.obj
1> BadComparison.exe : fatal error LNK1169: one or more multiply defined symbols found
(I'm using Visual Studio 2012)
Is the compiler creating a separate == operator for my Temperature class?
Thanks!